Whether to escape ( and ) in regex using GNU sed

后端 未结 4 1746
清歌不尽
清歌不尽 2020-12-08 14:53

I\'ve noticed several posts on this site which say that with gnu sed you should use ( and ) in regex rather than \\( and \\)

4条回答
  •  广开言路
    2020-12-08 15:36

    Escaped parentheses (\() make the regex search for parentheses as part of the expression.

    Unescaped parentheses (() make the regex group the contents of the parentheses together.

    In other words, if you escape them, the engine looks for them, but if you leave them as is, they cause the engine to group results into variables.

    An example to demonstrate:

    $myString = "junk(150)moar";

    To get just the number:
    #^\w+\((\d+)\)\w+$#

    ($1 is 150)

    It's a mess, I know, but it demonstrates the use of grouping parentheses and parentheses as part of the matching expression.

    Update Years Later:

    As user @bmk correctly points out, this answer applies to extended regular expressions, but not to basic regular expressions. It's difficult to find basic regular expressions as the default parsing engine in most programming languages, etc., but it would be prudent to verify which engine you are using before assuming this answer will apply to your situation.

提交回复
热议问题