Regex matches text containing a number but not ending with a question mark

I want to check if the text contains a number and is not a question, so I wrote the following Java code using a regular expression:

private static void containNumberNoQ(String commentstr){
     String urlPattern = "[^?]\\s\\d[^?]";
     Pattern p = Pattern.compile(urlPattern,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(commentstr);
        if (m.find()) {
            System.out.println("yes");
        }
}

But when I try this with the following sentence, it matches, although the sentence has a question mark:

just 2% of the result?

Why?

+4
source share
2 answers
^(?!.*?\\?).*\\d.*$

Try it. It will find sentences without ?and with numbers.

+2
source

Use the end of the string binding $. In addition, the number is \\dnot necessarily at the end of the question, so you need to match the possible characters between them.

\\b\\d.*[^?]$
+4
source

Source: https://habr.com/ru/post/1606983/


All Articles