TheDevWay
TheDevWay

Reputation: 1413

Regex to match all strings, strings with dots in between, and does not match strings with dash in between

I am trying to create a URL Routing rule for restful API.

I need a Regex that follows three simple rules:

  1. Match all strings
  2. Match strings with dots in between like android package names: com.test.package
  3. Does not match strings with dashes in between like: test-health

I've tried this rule it matches everything except android package name like strings. here is the rule:

<id:\\w+[.+]?>

P.S: I am using this Regex in Url Routing of Yii2 Framework which handles ^ and $ as the beginning and the ending of the Regex strings internally so I had to omit those.

Upvotes: 0

Views: 86

Answers (1)

revo
revo

Reputation: 48751

You made a mistake in building your character class where you added + in it. I assume you were trying to apply a quantifier but it doesn't work inside a character class. [.+]? means either a period or a literal + or nothing at all.

So if you remove that + your regular expression is close to work \w+\.?. But yet it doesn't match all consecutive occurrences of words and periods e.g. word.word.word and you have to quantify whole expression as well: (?:\w+\.?)+

The regex which fits your need at the most would be ^\w+(?:\.\w+)*$

Upvotes: 1

Related Questions