Regex - Capture only numbers that do not have letters next to them

I have a task to create a program that will correspond to numbers without numbers inside them. For instance:

6x ^ 2 + 6x + 6-57 + 8-9-90x

I am trying to use Regex to capture all numbers with + or - in front of them, but without x after that. I tried

\[+-](\d+)[^x] 

but it looks like it also displays "-90" from "-90x".

+5
source share
2 answers

The correct Regex will be as follows:

 @"[+-]((?>\d+))(?!x)" 

Alternative .NET solution:

 [+-](\d++)(?!x) 

 @" [+-] // Prefix non captured ( // Begin capturing group (?> // Begin atomic (non-backtracking) group - this part is essential \d+ // One or more digits ) // End atomic group ) // End capturing group (?! // Begin negative lookahead x // 'x' literal ) // End negative lookahead " 

You can test it here.

+8
source

The main problem with the original regular expression is that [ escaped, and so the literal [ matched, and another problem is related to (\d+)[^x] , which captures 1 + digits and is written to group 1 and then a [^x] matches any char, but x . This means that it can also match a digit (as in your case with -90x , [+-] matches - , (\d+) matches and captures 9 and [^x] matches 0 ).

A more suitable regular expression is to include the \d pattern with x in the negative view:

 [+-](\d+)(?![\dx]) 

See the demo of regex .

Template Details :

  • [+-] - either + or -
  • (\d+) - Capture group 1 corresponding to 1 or more digits
  • (?![\dx]) - a negative result that does not match if the numbers 1 + follow the number or x .
0
source

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


All Articles