Save parts of a String to variables using regular expressions

1

I need to save parts of a String in different variables using a single regular expression, the string is the following and it can vary, but the structure will always be the same (this line is stored in the variable strLineProcess):

Skype.exe pid: 1404 WATCHOUT\tofetopo

I have the following code:

final String regex = "^(\S*)";
final String processDetails = strLineProcess;
String processName = null;
String processID = null;
String computerName = null;
String currentUser = null;

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(processDetails);

if (matcher.find()) {
    processName = matcher.group(1);
    processID = matcher.group(2);
    computerName = matcher.group(3);
    currentUser = matcher.group(4);
}

The regular expression in the regex variable correctly matches the name of the process, but I do not know how to concatenate regular expressions to save the following parts of the String. For example, the regular expression ((\S*)+([0-9])) matches the processID (which in this example would be 1404), but I need to concatenate it with the first expression to have everything in one, just as I should do with computerName and currentUser, and here is where I'm lost . Any ideas?

The expected output in this example is:

processName = Skype.exe
processID = 1404
computerName = WATCHOUT
currentUser = tofetopo

The name of the process can be any up to the first space, the processID only numbers, computerName always appears just after the processID and even before the "\" , and the currentUser everything that comes after the "\" .

    
asked by Tofetopo 09.02.2017 в 13:29
source

1 answer

2

Regex:

^(\S+) pid: (\d+) ([^\\s]+)\(.+)
  • ^ - Start of the text
  • (\S+) - Characters that are not blank spaces, captured in group 1
  • pid: - matches the literal text
  • (\d+) - Digits, captured in group 2
  • ([^\\s]+) - Characters that are not \ or blank spaces, captured in group 3
  • \ - Matches a \ literal
  • (.+) - 1 or more characters, captured in group 4


Code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "^(\S+) pid: (\d+) ([^\\\s]+)\\(.+)";
final String processDetails = "Skype.exe pid: 1404 WATCHOUT\tofetopo";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(processDetails);

if (matcher.find()) {
    processName = matcher.group(1);
    processID = matcher.group(2);
    computerName = matcher.group(3);
    currentUser = matcher.group(4);
}

Demo:

link

    
answered by 09.02.2017 / 14:01
source