mikbal
mikbal

Reputation: 1198

Regex match exactly two colons

I have these strings, I want to return regex confirm those patterns.

NS::varible.child // OK
variable.child // OK
NS:variable.child // NO MATCH
::variablename.child // OK
:variablename.child // NO MATCH
_variablename.child.x // OK
5variablename.child.x // NO MATCH

I want C++ variable name match without -> operator and template<>

I have come up with this regular expression.

[a-z\_:{2,2}A-Z][a-z\_A-Z0-9\.:{2,2}]*

:{2,2} doesn't seem to be doing what I want. It accepts a single colon too.

How do I check exactly two colons? Even better a regex to match C++ variable constructs?

Upvotes: 1

Views: 3757

Answers (3)

spots
spots

Reputation: 2708

^(\w+|::)(::|.)\w+.\w+

Give that a try. You can use "::" literally to match two ":"

Upvotes: 2

Chris Pfohl
Chris Pfohl

Reputation: 19064

Like @Wiseguy said you can't use special characters inside a character class (the [ ]). The correct solution is to use a grouping to alternate between your literal and the character class:

([a-zA-Z]|::)

EDIT: More fully explained

If you think about a character class it's just a specialized way of writing a group anyway:

(a|b|c|d|e|f|g)

is identical to:

[a-g]

so by using a group for extra characters you'll achieve the same thing.

Upvotes: 1

detunized
detunized

Reputation: 15289

One of the options:

/^((::)?[_a-zA-Z.]+)+$/

Play with it online on Rubular.

Upvotes: 2

Related Questions