简体   繁体   中英

Regex to match a digit not followed by a dot(“.”)

I have a string

string 1 (excluding the quotes) -> "my car number is # 8746253 which is actually cool"

conditions - The number 8746253, could be of any length and
- the number can also be immediately followed by an end-of-line.

I want to group-out 8746253 which should not be followed by a dot "."
I have tried,

.*#(\\d+)[^.].*

This will get me the number for sure, but this will match even if there is a dot, because [.^] will match the last digit of the number(for example, 3 in the below case)

string 2 (excluding the quotes) -> "earth is # 8746253.Kms away, which is very far"

I want to match only the string 1 type and not the string 2 types.

To match any number of digits after # that are not followed with a dot, use

(?<=#)\d++(?!\.)

The ++ is a possessive quantifier that will make the regex engine only check the lookahead (?!\\.) only after the last matched digit, and won't backtrack if there is a dot after that. So, the whole match will get failed if there is a dit after the last digit in a digit chunk.

See the regex demo

To match the whole line and put the digits into capture group #1:

.*#(\d++)(?!\.).*

See this regex demo . Or a version without a lookahead:

^.*#(\d++)(?:[^.\r\n].*)?$

See another demo . In this last version, the digit chunk can only be followed with an optional sequence of a char that is not a . , CR and LF followed with any 0+ chars other than line break chars ( (?:[^.\\r\\n].*)? ) and then the end of string ( $ ).

This works like you have described

public class MyRegex{   
    public static void main(String[] args) {
        Pattern patern = Pattern.compile("#(\\d++)[^\\.]");
        Matcher matcher1 = patern.matcher("my car number is #8746253 which is actually cool");
        if(matcher1.find()){
            System.out.println(matcher1.group(1));
        }
        Matcher matcher2 = patern.matcher("earth is #8746253.Kms away, which is very far");
        if(matcher2.find()){
            System.out.println(matcher1.group(1));
        }else{
            System.out.println("No match found");
        }
    }
}

Outputs:

> 8746253 
> No match found

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM