Sebastian Thomas
Sebastian Thomas

Reputation: 1324

Regex match being overwritten

I'm trying to sanitise a phone number using Regex.

I don't want any separating characters between digits and I don't want the local (0) part. Separators could be any non-digit character.

ie. the number could be:

This matches the (0) part fine:

http://regex101.com/r/cB6hN4/3

But if I add |\D+ to match a non-digit character, it overwrites my first match:

http://regex101.com/r/cB6hN4/2

How do I keep both matches within in the one regex?

Upvotes: 0

Views: 62

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174816

I think you want something like this,

\((\d+)\)|(?:(?!\(\d+\))\D)+

DEMO

(?:(?!\(\d+\))\D)+ matches one or more non-digit characters but not of (\d+)

Upvotes: 1

Oscar Hermosilla
Oscar Hermosilla

Reputation: 530

Instead of using |\D+ at the end try to use |[^()\d]+

The regex will be \((\d+)\)|[^()\d]+

DEMO

But take into account that the parenthesis could not be used as a separator as you can see in the demo

Upvotes: 2

Related Questions