Hi I am new to java regex. I have the below string
String s = " "KBC_2022-12-20-2004_IDEAL333_MASTER333_2022-12-20-1804_SUCCESS";
I wanted to only Print "333" which is appended with MASTER . The output should be 333. Can someone help me writing the regex for this . Basically the code should print the value between "MASTER" and the next "_". here its 333 but the value might be of any number of character not limit to length 3.
CodePudding user response:
You can do MASTER(\\d )_
Pattern p = Pattern.compile("MASTER(\\d )_");
Matcher m = p.matcher(" KBC_2022-12-20-2004_IDEAL333_MASTER333_2022-12-20-1804_SUCCESS");
if (m.find()) {
System.out.println(m.group(1)); // 333
}
m = p.matcher(" KBC_2022-12-20-2004_IDEAL333_MASTER123_2022-12-20-1804_SUCCESS");
if (m.find()) {
System.out.println(m.group(1)); // 123
}
CodePudding user response:
You can use this regex: (?<=MASTER)[0-9] (?=\_)
.
We are looking for everything between MASTER
and _
:
- lookbehind: everything that goes after
MASTER
:(?<=MASTER)
- lookahead: everything that goes before
_
:(?=\_)
Try on regex101.com