views:

55

answers:

2

I have to validate username in my app so that it cannot contain two consecutive period symbols. I tried the following.

 username.match(/(..)/)

but found out that this matches "a." and "a..". I expected to get nil as the output of the match operation for input "a.". Is my approach right ?

+5  A: 

You need to put a \ in front of the periods, because period is a reserved character for "any character except newline".

So try:

username.match(/(\.\.)/)
dcp
Thank you very much. Works perfect !
alokswain
A: 

Short answer

You can use something like this (see on rubular.com):

username.match(/\.{2}/)

The . is escaped by preceding with a backslash, {2} is exact repetition specifier, and the brackets are removed since capturing is not required in this case.


On metacharacters and escaping

The dot, as a pattern metacharacter, matches (almost) any character. To match a literal period, you have at least two options:

  • Escape the dot as \.
  • Match it as a character class singleton [.]

Other metacharacters that may need escaping are | (alternation), +/*/?/{/} (repetition), [/] (character class), ^/$ (anchors), (/) (grouping), and of course \ itself.

References


On finite repetition

To match two literal periods, you can use e.g. \.\. or [.][.], i.e. a simple concatenation. You can also use the repetition construct, e.g. \.{2} or [.]{2}.

The finite repetition specifier also allows you write something like x{3,5} to match at least 3 but at most 5 x.

Note that repetition has a higher precedence that concatenation, so ha{3} doesn't match "hahaha"; it matches "haaa" instead. You can use grouping like (ha){3} to match "hahaha".


On grouping

Grouping (…) captures the string it matches, which can be useful when you want to capture a match made by a subpattern, or if you want to use it as a backreference in the other parts of the pattern.

If you don't need this functionality, then a non-capturing option is (?:…). Thus something like (?:ha){3} still matches "hahaha" like before, but without creating a capturing group.

If you don't actually need the grouping aspect, then you can just leave out the brackets altogether.

polygenelubricants