Regex for identifying numbers, unless they are enclosed in "[" "]"

I want to write a regular expression so that I match only the first number NOT, enclosed in square brackets.

eg. asdadsas,*&(*&(*2asdasd*U(*&*()&(*3 must match 2 (without square brackets)

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

The regular expression that I still have is: (?<!\[)[0-9](?!\])

However, the problem is that [2 must match 2.

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

I do not know how (or, if possible, it is possible) to implement similar conditional logic in a regular expression.

+6
source share
5 answers

The following should work:

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

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

Explanation: [0-9] corresponds to a digit, (?!(?<=\[.)\]) Establishes the requirement that the character before and after this digit should not be [ and ] respectively. To break this down, consider the following regular expression:

 (?<=\[.)\] 

This can be read as "match a ] , but only if the symbol two places back was [ ". Putting it in a negative look right after we match the number, we can fail if the symbol two places ago was [ , and the next symbol is ] .

+2
source

Only a Regex solution would be redundant

Just use (^|\D)(\d+)($|\D) and then select the first one that matches your criteria.

In C # you can do it this way

 string output=Regex.Matches(input,@"(^|\D)(\d+)(\D|$)") .Cast<Match>() .Where(x=>!(x.Value.StartsWith("[")&& x.Value.EndsWith("]"))) .First() .Groups[2] .Value; 
0
source
 (?! # start negative lookahead \[ # open bracket \d # digit (use \d+ if needed) \] # close bracket ) # end negative lookahead \[ # literal bracket (\d) # capture digit | # alternation (OR) (?<! # start negative lookbehind \[ # literal bracket ) (\d) # capture digit 

This will fix the numbers as backlinks. If you need a figure for full compliance, you can probably use viewing.

http://rubular.com/r/C8YSRiY1d0

0
source

Try to use appearance and alternation. This corresponds to either a figure that is not preceded by [ , or a figure that does not follow ] :

 (?<!\[)\d|\d(?!\]) 

In order for it to work with digits of more than one digit, you need to add overview elements so that the previous / next character is neither a bracket, nor a digit:

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

namely (using Ruby, should work similarly elsewhere):

 >> rex = /(?<!\[|\d)\d+|\d+(?!\]|\d)/ >> "&(*25asdasd*U(*&*()&(*3".match rex #=> #<MatchData "25"> >> "&(*[25asdasd*U(*&*()&(*3".match rex #=> #<MatchData "25"> >> "&(*25]asdasd*U(*&*()&(*3".match rex #=> #<MatchData "25"> 

but

 >> "&(*[25]asdasd*U(*&*()&(*3".match rex #=> #<MatchData "3"> 
0
source

I believe the simplest regular expression that should be for you:

 (?<!\[)[0-9]+|[0-9]+(?!\]) 

Live Demo: http://www.rubular.com/r/xWXFg7QXZJ

0
source

Source: https://habr.com/ru/post/957697/


All Articles