How to Match Repeated Patterns?

How to Match Repeated Patterns?

I would like to match:

some.name.separated.by.dots

But I don't have any idea how.

I can match a single part like this

 \w+\.

How can I say "repeat that"

4

4 Answers

Try the following:

\w+(?:\.\w+)+

The + after (?: ... ) tell it to match what is inside the parenthesis one or more times.

Note that \w only matches ASCII characters, so a word like café wouldn't be matches by \w+, let alone words/text containing Unicode.

EDIT

The difference between [...] and (?:...) is that [...] always matches a single character. It is called a "character set" or "character class". So, [abc] does not match the string "abc", but matches one of the characters a, b or c.

The fact that \w+[\.\w+]* also matches your string is because [\.\w+] matches a . or a character from \w, which is then repeated zero or more time by the * after it. But, \w+[\.\w+]* will therefor also match strings like aaaaa or aaa............

The (?:...) is, as I already mentioned, simply used to group characters (and possible repeat those groups).

More info on character sets:

More info on groups:

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.