How to write "and" in Regex. Like we can write "or" using pipe | similarly is there a way to write "and"
I have
- REGEX1 :
^(?!([0-9])\1{2}[-. ]*\1{3}[-. ]*\1{4}$)
which validates anything except numbers like 111-111-1111 or 111.111.1111 and another - REGEX2:
^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$
which validates numbers like 784-223-4567
I want the digit string to be valid only if both REGEX1 && REGEX2 conditions are satisfied
Answer
The default regex standard (as defined by Kleene) has no way to write and: it only has the concatenation, disjunction and Kleene star. You can however apply the regex engine multiple times. For instance:
grep "regex1" < file | grep "regex2"
So using a pipe the first grep
filters all lines that match the first regex, and the second grep
filters the result even deeper.
If you use an extended version of regexes (with positive lookahead), you can implement the and-pattern:
(?=regex1)(?=regex2)regex3
Perl and most other P-languages support this pattern. But most other languages don't.
EDIT: based on your comment, and using the second pattern, the regex reads:
^(?=(?!([0-9])\1{2}[-. ]*\1{3}[-. ]*\1{4}$))\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$
No comments:
Post a Comment