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

manoj :

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.

Wiktor Stribiżew :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=440638&siteId=1