0

Iam trying to get the pid of some process.

This is the output of the process

pkill -f ./scene
scene killed (pid 11619)
scene killed (pid 31533)

from this i want to retrieve 11619 and 31533 as list. I prefer to do it via regex. How can I create regex for this?

Psl
  • 3,366
  • 13
  • 39
  • 69
  • 2
    Does this answer your question? [Learning Regular Expressions](https://stackoverflow.com/questions/4736/learning-regular-expressions) – sleepToken Jan 29 '20 at 15:54
  • this too [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – Cid Jan 29 '20 at 15:57
  • Is `pkill -f ./scene` part of the output? – Bohemian Jan 29 '20 at 16:12

2 Answers2

2

You actually can do this entirely in Java:

List<Long> killedPids = ProcessHandle.allProcesses()
    .filter(p -> p.info().commandLine()
        .filter(cmd -> cmd.equals("./scene"))
        .isPresent()
        && p.destroy())
    .map(ProcessHandle::pid)
    .collect(Collectors.toList());

No regular expressions needed. And no need to depend on the format of external commands’ output.

VGR
  • 33,718
  • 4
  • 37
  • 50
1

To get you started, it will look something like this. This is the most basic regex that is looking for exactly 5 digits as a PID.

Obviously, we are assuming here that a PID is always 5 digits, and that every sequence of 5 digits is going to be a PID.

If you want to get more fool-proof, you might play around with regex searching for the "pid" prefix and some suffix, and then trimming that String accordingly.

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    static String PATTERN = "[0-9]{5}";

    static String test =    "pkill -f ./scene\r\n" + 
                            "scene killed (pid 11619)\r\n" + 
                            "scene killed (pid 31533)";

    public static void main(String[] args) {
        List<String> matches = new ArrayList<String>();

        Matcher m = Pattern.compile(PATTERN).matcher(test);

        while (m.find()) matches.add(m.group());

        System.out.println(matches);
    }
}

Gives us the output:

[11619, 31533]
sleepToken
  • 1,804
  • 1
  • 12
  • 21