Regex: how to use lookahead / lookbehind according to template result?

I am trying to learn more about regex today.

I'm just trying to match an order number not surrounded by brackets ( #1234but not [#1234]), but my question mainly concerns the use of lookahead statements for an arbitrary template.

In my first attempts, I noticed that my negative coincidence \d+(?!\])will lead to the fact that it \d+will contain the corresponding numbers until it follows ]. I need the numbers to match only if their whole is not followed ].

My current solution kills the match on the first digit, looking ahead if there is any in the string of numbers ].

Is this the standard way to do this? I just repeat the match pattern in lookahead. If it were a more complex regular expression, would I approach it the same way? Repeat the actual match, followed by an invalid match, and repeat the regular expression for each letter?

For actual matches, he would have to match himself as many times as the characters in the match.

(?<!\[) # not preceded by [
#\d+ 
(?!\d*\]) # not followed zero+ digits and ] 

# or (?!\d|\]) # not followed by digit or ]

I would appreciate any feedback!

+5
source share
1 answer

You can achieve what you want using possessive quantifier along with such images

(?<!\[)#\d++(?!\])

, \d+, #123. , , , / .

Live Demo

Edit ,

#\d(?<!\[#\d)(?!\d*\])\d*
+8

All Articles