Jeremy
Jeremy

Reputation: 5435

Regex - matching while ignoring some characters

I am trying to write a regex to max a sequence of numbers that is 5 digits long or over, but I ignore any spaces, dashes, parens, or hashes when doing that analysis. Here's what I have so far.

(\d|\(|\)|\s|#|-){5,}

The problem with this is that this will match any sequence of 5 characters including those characters I want to ignore, so something like "#123 " would match. While I do want to ignore the # and space character, I still need the number itself to be 5 digits or more in order to qualify at a match.

To be clear, these would match:

1-2-3-4-5
123 45
2(134)   5

Bonus points if the matching begins and ends with a number rather than with one of those "special characters" I am excluding. Any tips for doing this kind of matching?

Upvotes: 3

Views: 10782

Answers (3)

Jale
Jale

Reputation: 1

You can suggest non-digits with \D so et would be something like:

(\d\D*){5,}

Here is a guide.

Upvotes: 0

ndnenkov
ndnenkov

Reputation: 36101

So just repeat a digit, followed by any other sequence of allowed characters 5 or more times:

^(\d[()\s#-]*){5,}$

You can ensure it ends on a digit if you subtract one of the repetitions and add an explicit digit at the end:

^(\d[()\s#-]*){4,}\d$

Upvotes: 2

anubhava
anubhava

Reputation: 784888

If I understood requirements right you can use:

^\d(?:[()\s#-]*\d){4,}$

RegEx Demo

It always matches a digit at start. Then it is followed by 4 or more of a non-capturing group i.e. (?:[()\s#-]*\d) which means 0 or more of any listed special character followed by a digit.

Upvotes: 3

Related Questions