Kong Konfus
Kong Konfus

Reputation: 87

Regex should find substring that does not start with /

I want to find version numbers in a long string. Example: "Hellothisisastring 12.3 blabla"

I need to find a substring that is a version number but does not start with "/".

Example: "Hellothisisastring /12.3 blabla" shouldn't match.

I already build following regex: [0-9]+.[0-9]

How can I detect a that the version number does not start with "/". The problem is that it is not at the beginning of the string. I already tried with negative lookahead.

(?!/)[0-9]+.[0-9] still matches with a slash before.

Thanks for any help :)

Upvotes: 0

Views: 143

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626729

You need to use a lookbehind and include a digit pattern to also fail the positions right after digits:

(?<![\d\/])[0-9]+\.[0-9]+

See the regex demo. Also, you may match any amount of . + digits using

(?<![\d\/])[0-9]+(?:\.[0-9]+)+

See this regex demo. Details:

  • (?<![\d\/]) - a negative lookbehind that fails the match if there is a digit or / immediately to the left of the current location
  • [0-9]+ - one or more digits
  • (?:\.[0-9]+)+ - one or more sequences of a . and one or more digits.

Upvotes: 1

Related Questions