What's the difference between () and [] in regular expression patterns?

后端 未结 6 2043
梦谈多话
梦谈多话 2020-12-01 00:57

What is the difference between encasing part of a regular expression in () (parentheses) and doing it in [] (square brackets)?

How does this:

[a-z0         


        
6条回答
  •  天涯浪人
    2020-12-01 01:06

    The [] construct in a regex is essentially shorthand for an | on all of the contents. For example [abc] matches a, b or c. Additionally the - character has special meaning inside of a []. It provides a range construct. The regex [a-z] will match any letter a through z.

    The () construct is a grouping construct establishing a precedence order (it also has impact on accessing matched substrings but that's a bit more of an advanced topic). The regex (abc) will match the string "abc".

提交回复
热议问题