user4428063
user4428063

Reputation:

Regex - Capture only numbers that don't have a letter next to them

I have a task to create program that'll match digits without numbers infront of them. For example:

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

I'm trying to use Regex to capture all numbers with + or - before them - but without x afterwards. I've tried

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

but it seems to capture the '-90' from '-90x' as well.

Upvotes: 5

Views: 1171

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

The main issue with the original regex is that the [ is escaped and a literal [ is thus matched, and another problem is with (\d+)[^x] that captures 1+ digits and captured into Group 1 and then a [^x] matches any char but x. It means it may also match a digit (as in your case, with -90x, the [+-] matches -, (\d+) matches and captures 9 and [^x] matches 0).

A more appropriate regex is to include a \d pattern with x into the negative lookahead:

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

See the regex demo.

Pattern details:

  • [+-] - either + or -
  • (\d+) - Capturing group 1 matching 1 or more digits
  • (?![\dx]) - A negative lookahead that fails the match if 1+ digits are followed with a digit or x.

Upvotes: 1

maraaaaaaaa
maraaaaaaaa

Reputation: 8163

The correct Regex would be this:

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

Alternative non- .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

Upvotes: 8

Related Questions