Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to identify numbers except when enclosed by "[" "]"

Tags:

regex

I want to write a regex such that I only match the first number NOT enclosed by square brackets.

e.g. asdadsas,*&(*&(*2asdasd*U(*&*()&(*3 should match 2 ( no square brackets )

and asdadsas,*&(*&(*[2]asdasd*U(*&*()&(*3 should match 3

The regex I have so far is : (?<!\[)[0-9](?!\])

However, the problem I have is that [2 should still match 2.

I only want to skip the number if it has a [ to the left AND a ] to the right.

I don't know how ( or if its even possible) to implement this kind of conditional logic in a regex.

like image 676
Marc HPunkt Avatar asked Nov 08 '13 17:11

Marc HPunkt


1 Answers

The following should work:

[0-9](?!(?<=\[.)\])

Example: http://rubular.com/r/0vKy8hyMy0

Explanation: [0-9] matches a digit, (?!(?<=\[.)\]) enforces the requirement that the character before and after that digit are not [ and ] respectively. To break this down, consider the following regex:

(?<=\[.)\]

This can be read as "match a ] but only if the character two places ago was a [". By putting this into a negative lookahead just after we match the digit, we can fail if the character two places ago was a [ and the next character is a ].

like image 174
Andrew Clark Avatar answered Oct 21 '22 06:10

Andrew Clark