简体   繁体   中英

Extracting numbers from String through Regex in Java

I have created a program which gets the string from the putty and kills the processID from getting processID from that string. Currently it is working fine but sometimes it is not reliable.

Please find the target and the regex I used below.

Target String : root 14139 1 25 Aug03 ? 06:47:50 /usr/local root 14139 1 25 Aug03 ? 06:47:50 /usr/local

RegEx I used : \\\\\\d{3,5}

I want to get the RegEx which can find the immediate number after root and ignore the other text. (eg, I want to extract 14139 from the example string removing all the extra space.)

How can I do it?

So you need the a number from the second field delimited by spaces. The following regex gets it in the capture group 1:

^\S+\s+(\d+)

Demo: https://regex101.com/r/bE7xL8/1

And the sample Java code:

String input = "root 14139 1 25 Aug03 ? 06:47:50 /usr/local";
Pattern pattern = Pattern.compile("^\\S+\\s+(\\d+)");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
    System.out.println(matcher.group(1));
}

Demo: https://ideone.com/LVLCNm

I suggest this one:

^root (\d*)\D?.*

capture 1 or more digits after a starting " root " string and delimited by not-digit chars

tester: https://regex101.com/r/sL8oJ7/1

再次使用捕获组,这会更加宽容,并减少对空间数量的依赖:

root[^\\d]*(\\d+)

You can use following regex and used first group : root[^\\S]*(\\d+)

Demo and Example

Try this for your target string its giving output as required by you.

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

class exampleproblem {
public static void main(String[] args) {
    String target = "root 14139 1 25 Aug03 ?        06:47:50 /usr/local";
    String regexex = "root(.[0-9]+)";
    Pattern pattern = Pattern.compile(regexex);
    Matcher matcher = pattern.matcher(target);
    while (matcher.find()) {
        System.out.println(matcher.group(1).trim());
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM