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.
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 ].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With