开发者

Regex to check consecutive occurrence of period symbol in username

开发者 https://www.devze.com 2023-01-10 20:29 出处:网络
I have to validate username in my app so that it cannot contain two consecutive period symbols. I tried the following.

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 ap开发者_开发问答proach right ?


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(/(\.\.)/)


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

  • regular-expressions.info/Literals and metacharacters, Dot: ., Character Class: […], Anchors: ^$, Repetition: *+?{…}, Alternation: |, Optional: ?, Grouping: (…)

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消