Reputation: 41
i need a regular expression to validate the field. It is a field of phone numbers, the number consists of 9 characters, numbers will be separated by commas.
Example:
123456789,123456789,123456789
123456789
123456789,123456789
I have written:
~^(([0-9]{9,9},)+|([0-9]{9,9})+)$~i
but validating passes only numbers with commas.
Example:
123456789,123456789,
123456789,
Can you help me with this?
Upvotes: 1
Views: 1957
Reputation: 626950
You need to set a *
quantifier to the first 9-digit group:
~^(?:[0-9]{9},)*[0-9]{9}$~
^
See the regex demo. No need in ~i
case insensitive modifier, there are no letters in the pattern. Also, {9,9}
= {9}
.
The same pattern can be written as
~^[0-9]{9}(?:,[0-9]{9})*$~
See another demo.
Details:
^
- start of string(?:[0-9]{9},)*
- 0+ sequences of:
[0-9]{9}
- 9 digits,
- comma[0-9]{9}
- 9 digits$
- end of string (may be replaced with \z
to match the very end of string).EDIT: Since you only want to match comma-separated 9-digit chunks that only contain unique digits, it is possible to write a regex for that, although it is not recommended to use it. Best is to use your programming language means for that.
A regex will look like (verbose version):
^ # start of string
( # Group 1 start
(\d) # Digit 1 captured into Group 2
(?!\2)(\d) # Digit 2 not equal to the first one
(?!\2|\3)(\d) # etc.
(?!\2|\3|\4)(\d)
(?!\2|\3|\4|\5)(\d)
(?!\2|\3|\4|\5|\6)(\d)
(?!\2|\3|\4|\5|\6|\7)(\d)
(?!\2|\3|\4|\5|\6|\7|\8)(\d)
(?!\2|\3|\4|\5|\6|\7|\8|\9)(\d)
)
(?:,(?1))* # 0+ sequences of , and the Group 1 pattern
$ # End of string
See the regex demo. A one-liner:
^((\d)(?!\2)(\d)(?!\2|\3)(\d)(?!\2|\3|\4)(\d)(?!\2|\3|\4|\5)(\d)(?!\2|\3|\4|\5|\6)(\d)(?!\2|\3|\4|\5|\6|\7)(\d)(?!\2|\3|\4|\5|\6|\7|\8)(\d)(?!\2|\3|\4|\5|\6|\7|\8|\9)(\d))(?:,(?1))*$
In PHP, you may just use
if (count( array_unique( str_split( $s))) == strlen($s)) {
echo "Unique";
} else {
echo "Not unique";
}
Upvotes: 3
Reputation: 2323
Just move that plus(+) to the end of the bigger group
^(([0-9]{9,9},)|([0-9]{9,9}))+$
Upvotes: 0
Reputation: 3596
I don't think that your regex has to be very complicated:
^\d{9}(,\d{9})*,?
Upvotes: 0