Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if specific pattern precedes some character?

I am new into java regex and I could't find an answer.

This is my regex: -?\\d*\\.?\\d+(?!i) and I want it not to recognize eg. String 551i

This is my method:

private static double regexMatcher(String s, String regex) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(s.replaceAll("\\s+", ""));

    if (!matcher.find()) {
        return 0;
    }
    String found = matcher.group();

    return Double.parseDouble(matcher.group());

}

I want this method to return 0.0 but it keeps returning 55.0.

What am I doing wrong?

like image 400
i_rezic Avatar asked Dec 09 '25 09:12

i_rezic


1 Answers

Use an atomic group to avoid backtracking into the whole digit dot digit matching pattern:

"-?(?>\\d*\\.?\\d+)(?!i)"

See the Java demo and a regex demo.

like image 91
Wiktor Stribiżew Avatar answered Dec 10 '25 21:12

Wiktor Stribiżew



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!