How can I use a look after to match either a single or a double quote?

前端 未结 3 565
天涯浪人
天涯浪人 2021-01-26 20:27

I have a series of strings I want to extract:

hello.this_is(\"bla bla bla\")
some random text
hello.this_is(\'hello hello\')
other stuff

What I

3条回答
  •  生来不讨喜
    2021-01-26 20:51

    Based on revo and hek2mgl excellent answers, I ended up using grep like this:

    grep -Po '(?<=hello\.this_is\((["'\''])).*(?=\1)' file
    

    Which can be explained as:

    • grep
    • -Po use Perl regexp machine and just prints the matches
    • '(?<=hello\.this_is\((["'\''])).*(?=\1)' the expression
      • (?<=hello\.this_is\((["'\''])) look-behind: search strings preceeded by "hello.this_is(" followed by either ' or ". Also, capture this last character to be used later on.
      • .* match everything...
      • (?=\1) until the captured character (that is, either ' or ") appears again.

    The key here was to use ["'\''] to indicate either ' or ". By doing '\'' we are closing the enclosing expression, populating with a literal ' (that we have to escape) and opening the enclosing expression again.

提交回复
热议问题