Vladislav Vladislav - 2 months ago 6
Java Question

Find special number in String using regEx

I'am having diffuculties with regular Expr. I must find 123 in string

String str = "abc.123,a"
. I tried
if(str1.matches("[\\s,.!]*123[\\s,.!]*"))
System.out.println("String " + str1 +" consist number " + searchNumber);

But it doesn't work, but if i have
String str = .123,
it works.

Answer

If you used Matcher#find() with your regex, you would get a match because find() searches for partial matches. However, since [\s,.!]* matches 0 or more occurrences, your pattern does not meet your i must find bare number(without letter near) requirement.

You might be interested in a word boundary based solution - "\\b123\\b". See this demo. Word boundaries match positions before/after letters, digits and underscores.

If you really need to match in between letters, use

String pat = "(?<!\\p{L})123(?!\\p{L})";

See the regex demo, where

See the Java demo:

String str = "abc.123,a";
Pattern ptrn = Pattern.compile("(?<!\\p{L})123(?!\\p{L})");
Matcher matcher = ptrn.matcher(str);
if (matcher.find()) {
    System.out.println("YES");
}