Reputation: 9503
I have to search string with format aaa.aaa.aaa. ...... n times
, "a" can be any alphanumeric or special char.
For the pattern I made ^.{3}(\..{3})*
regex
^.{3} => Starting first 3 chars can be any
(\..{3})* => Next should be dot and followed by 3 any chars ntimes (0 or more times repetitions)
The issue is regex pattern returns true if it matches first 3 chars and it ignores the optional condition. Is there any way to resolve the issue?
Regex101: https://regex101.com/r/KpI9VF/2
Python Code:
import re
import sys
regex_pattern = r"^.{3}(?:\..{3})*"
test_array = ["123.456.abc.def",
"1123.456.abc.def",
"123.125.528.256",
"asd.asd.asd.asd",
"123456789.2.2.2",
"123.125.528.256",
"123456789.2.2.2",
"...............",
"...",
"`!@.#$%.^&*.()_",
"1234.123.123.123",
"123.123.123.1234",
"...123.123.123.123..."
]
for test_string in test_array:
match_res = re.match(regex_pattern, test_string) is not None
print(test_string + " ==> " +str(match_res).lower())
Output:
123.456.abc.def ==> true
1123.456.abc.def ==> true
123.125.528.256 ==> true
asd.asd.asd.asd ==> true
123456789.2.2.2 ==> true
123.125.528.256 ==> true
123456789.2.2.2 ==> true
............... ==> true
... ==> true
`!@.#$%.^&*.()_ ==> true
1234.123.123.123 ==> true
123.123.123.1234 ==> true
...123.123.123.123... ==> true
Expected Output
123.456.abc.def true
1123.456.abc.def false
123.125.528.256 true
asd.asd.asd.asd true
123456789.2.2.2 false
123.125.528.256 true
123456789.2.2.2 false
............... true
... false
`!@.#$%.^&*.()_ true
1234.123.123.123 false
123.123.123.1234 false
...123.123.123.123... false
Upvotes: 0
Views: 126
Reputation: 627536
You can use
^.{3}(?:\..{3})+$
See the regex demo.
Details:
^
- start of string.{3}
- any 3 chars other than line break chars(?:\..{3})+
- one or more occurrences of
\.
- a .
char.{3}
- any 3 chars other than line break chars$
- end of string.See the regex graph:
Upvotes: 2
Reputation: 535
By the definition you gave in the question, ...
should match with the pattern. And what you also need is a string ending anchor $
.
I believe if you update your expression as r"^.{3}(\..{3})*$"
(Also removed ?:
), it works as intended.
Upvotes: 1