0

I want to allow only digits, spaces and these characters:
\
+
(
)

I'd like it to be a minimum of 6 digits. The digits can be anywhere in the string.

This is the closest I can get it:

^(?=.{6,})[0-9\-\+\(\\) ]*$

My code works except for the minimum of 6 digits requirement. (It just enforces a minimum of 6 characters.)

Input text that should not match:

+()1234

Input text that should match:

+(44) 78666-05529

Gail Foad
  • 511
  • 7
  • 21
  • 1
    You may use `@"^(?=(?:\D*\d){6})[-0-9+()\\ ]*$"`, see [this regex demo in .NET regex tester](http://regexstorm.net/tester?p=%5e%28%3f%3d%28%3f%3a%5b%5e%5cd%5cn%5d*%5cd%29%7b6%7d%29%5b-0-9%2b%28%29%5c%5c+%5d*%5cr%3f%24&i=%2b%28%291234%0d%0a%2b%2844%29+78666-05529&o=m). Or, use `^[-+()\\ ]*(?:[0-9][-+()\\ ]*){6,}$`. See [another regex demo](http://regexstorm.net/tester?p=%5e%5b-%2b%28%29%5c%5c+%5d*%28%3f%3a%5b0-9%5d%5b-%2b%28%29%5c%5c+%5d*%29%7b6%2c%7d%5cr%3f%24&i=%2b%28%291234%0d%0a%2b%2844%29+78666-05529&o=m). – Wiktor Stribiżew Jan 10 '19 at 16:53
  • 1
    I think there is a two better solutions, but I cant post them because this question is now locked. First can be [tried online](https://tio.run/##hY6xCsIwFEV3v@LRoSSUhhrbtCIVpS6Cu4tLqEEfhESaVD8/tnbRQV0v5557W5e2DkO4yw6k1vahzs1Vdg5q2ESnJCUUsjlf5IUoq2W0mo0cmlvvByBKSJ5TKCshRJoVBf8A@ETQsT3kjTXOasWOHXp1QKPIi2KN7Y0n4ybbux1e0FNY1yAgjicP22pN3q8NFeMlGkfpVy3/7@U/xSE8AQ "C# (Visual C# Interactive Compiler) – Try It Online") and the second is to use libphonenumber instead of a homemade algorithm to check phone number.. – aloisdg Jan 10 '19 at 17:06

1 Answers1

2

Your current lookahead ^(?=.{6,}) asserts that what follows is 6 or more times times any character from the start of the string.

If the digits can be anywhere in the string you have to assert a digit 6 times using a positive lookahead and a non capturing group (?:.*[0-9]){6}.

Note that this does not take care of the exact formats of the numbers in the example data.

^(?=(?:.*[0-9]){6})[0-9\-+(\\) ]*$

Regex demo

The fourth bird
  • 96,715
  • 14
  • 35
  • 52