Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 345
manoj Avatar asked Aug 07 '17 09:08

manoj


2 Answers

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 ($).

like image 173
Wiktor Stribiżew Avatar answered Oct 22 '22 06:10

Wiktor Stribiżew


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
like image 1
Antoniossss Avatar answered Oct 22 '22 05:10

Antoniossss