简体   繁体   中英

unexpected regex match

Can anyone explain why the following test is not passing. The regex is getting a match where I do not want one.

I want to find a match on text that begins with Tel, Fax or Web but for some reason, the url in the test is getting a match:

  def test_url_should_match
    assert_no_match(/^[tel|fax|web]/i, "www.jehall.co.uk")
  end

[...] in a regular expression specifies a character class , which tells the regular expression engine to match one of these characters contained within brackets. Therefore, [tel|fax|web] means "match t or e or l or | or f or a or x or w or e or b" (the fact that | appears more than once in the class is irrelevant). Since the string starts with aw -- which is in the character class -- the pattern matches.

As other answers have said, you want to use parentheses (...) to group your alternation instead.

Try it with

assert_no_match(/^(tel|fax|web)/i, "www.jehall.co.uk")

That should work. Otherwise you're matching against the characters, ie the w in web will match.

你应该用

/^(?:tel|fax|web)/i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM