Using trim() in Java to remove parts of an ouput

3.7k views Asked by At

I have some code I wrote that outputs a batch file output to a jTextArea. Currently the batch file outputs an active directory query for the computer name, but there is a bunch of stuff that outputs as well that I want to be removed from the output from the variable String trimmedLine. Currently it's still outputting everything else and I can't figure out how to get only the computer name to appear.

Output: "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET"

I want the output to instead just show only this:

FDCD111304

Can anyone show me how to fix my code to only output the computer name and nothing else? Look at console output (Ignore top line in console output) Look at console output

    btnPingComputer.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

            String line;
            BufferedWriter bw = null;
            BufferedWriter writer =null;
            try {
                writer = new BufferedWriter(new FileWriter(tempFile));
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            String lineToRemove = "OU=Workstations";
            String s = null;
            Process p = null;

            try {

                p = Runtime.getRuntime().exec("c:\\computerQuery.bat");

            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }
            StringBuffer sbuffer = new StringBuffer(); // new trial
            BufferedReader in = new BufferedReader(new InputStreamReader(p
                    .getInputStream()));

            try {

                while ((line = in.readLine()) != null) {

                    System.out.println(line);

                    textArea.append(line);
                    textArea.append(String.format("  %s%n", line));
                    sbuffer.append(line + "\n");
                    s = sbuffer.toString();
                    String trimmedLine = line.trim();
                    if(trimmedLine.equals(lineToRemove)) continue;
                    writer.write(line + System.getProperty("line.separator"));
                }
                fw.write("commandResult is " + s);
                 String input = "CN=FDCD511304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
                    Pattern pattern = Pattern.compile("(.*?)\\=(.*?)\\,");
                    Matcher m = pattern.matcher(input);

                    while(m.find()) {

                        String currentVar = m.group().substring(3, m.group().length() - 1);
                        System.out.println(currentVar); //store or do whatever you want
                    }
            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } finally

            {
                try {
                    fw.close();

                }

                catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            try {

                in.close();

            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

        }

    });
5

There are 5 answers

2
Max Fichtelmann On

You could also use javax.naming.ldap.LdapName when dealing with distinguished names. It also handles escaping which is tricky with regex alone (i.e. cn=foo\,bar,dc=fl,dc=net is a perfectly valid DN)

String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(ldapName.size() - 1).getValue();
2
Raniz On

You can use a different regular expression and Matcher.matches() to find only the value you're looking for:

String str = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
Pattern pattern = Pattern.compile("(?:.*,)?CN=([^,]+).*");
Matcher matcher = pattern.matcher(str);
if(matcher.matches()) {
    System.out.println(matcher.group(1));
} else {
    System.out.println("No value for CN found");
}

FDCD111304

That regular expression will find the value for CN regardless of where in the string it is. The first group is to discard anything in front of CN= (we use a group starting with ?: here to indicate that the contents of the group should not be kept), then we match CN=, then the value, which may not contain a comma and then the rest of the string (which we don't care about).

You can also use a different regex and Matcher.find() to get both the keys and values and choose which keys to act on:

String str = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
Pattern pattern = Pattern.compile("([^=]+)=([^,]+),?");
Matcher matcher = pattern.matcher(str);

while (matcher.find()) {
    String key = matcher.group(1);
    String value = matcher.group(2);
    if("CN".equals(key) || "DC".equals(key)) {
        System.out.printf("%s: %s%n", key, value);
    }
}

CN: FDCD111304
DC: FL
DC: NET

0
Mohammed Sohail Ebrahim On

Try using substring to chop off the parts you dont require hence creating a new string

0
TSwift On

Well I would personally use the split() function to first get the parts split up and then parse out again. So my (probably unprofessional and buggy code) would be

String args[] = line.split(",");
String args2[] = args[0].split("=");
String computerName = args2[1];

And that would be where this is:

while ((line = in.readLine()) != null) {

                System.out.println(line);
                String trimmedLine = line.trim();
                if (trimmedLine.equals(lineToRemove))
                    continue;
                writer.write(line
                        + System.getProperty("line.separator"));
                textArea.append(trimmedLine);
                textArea.append(String.format("  %s%n", line));

            }
2
3mpty On

There're few options, simples dumbest:

str.substring(str.indexOf("=") + 1, str.indexOf(","))

Second one and more flexible approach would be to build HashArray, it would be helpful in future to read other values.

Edit: Second method

import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.HashMap;

public class HelloWorld{

 public static void main(String []args){
    String input = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
    Pattern pattern = Pattern.compile("(.*?)\\=(.*?)\\,");
    Matcher m = pattern.matcher(input);

    while(m.find()) {

        String currentVar = m.group().substring(0, m.group().length() - 2);
        System.out.println(currentVar); //store or do whatever you want
    }
 }
}

This one will print all values like CN=FDCD11130, you can split it by '=' and store in key/value container like HashMap or just inside list.