Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regular expression word match

Tags:

java

regex

I have 3 values IU, PRI and RET. if my input string contains any one or more value(s),
the Java regular expression should return true.

Ex:
Values : IU PRI RET 
Input String : "put returns UI between paragraphs"

The Input string contains "UI" word, the Java regular expression should return true.

like image 755
Ravichandra Avatar asked Mar 18 '26 10:03

Ravichandra


2 Answers

You need word boundaries for that:

boolean foundMatch = false;
Pattern regex = Pattern.compile("\\b(?:UI|PRI|RET)\\b");
Matcher regexMatcher = regex.matcher(subjectString);
foundMatch = regexMatcher.find();
like image 185
Tim Pietzcker Avatar answered Mar 20 '26 23:03

Tim Pietzcker


Try

String s= "A IU somehting PRI something RET whatever";

Pattern p= Pattern.compile("(IU|PRI|RET)");
Matcher m= p.matcher(s);
while (m.find()) {
    String matched= m.group(1);
    System.out.println(matched);
}

It prints:

IU
PRI
RET
like image 34
darijan Avatar answered Mar 20 '26 23:03

darijan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!