Regex: To pull out a sub-string between two tags in a string

后端 未结 9 1976
情书的邮戳
情书的邮戳 2020-12-08 00:35

I have a file in the following format:

Data Data
Data
[Start]
Data I want
[End]
Data

I\'d like to grab the Data I want from between the

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 00:47

    A more complete discussion of the pitfalls of using a regex to find matching tags can be found at: http://faq.perl.org/perlfaq4.html#How_do_I_find_matchi. In particular, be aware that nesting tags really need a full-fledged parser in order to be interpreted correctly.

    Note that case sensitivity will need to be turned off in order to answer the question as stated. In perl, that's the i modifier:

    $ echo "Data Data Data [Start] Data i want [End] Data" \
      | perl -ne '/\[start\](.*?)\[end\]/i; print "$1\n"'
     Data i want 
    

    The other trick is to use the *? quantifier which turns off the greediness of the captured match. For instance, if you have a non-matching [end] tag:

    Data Data [Start] Data i want [End] Data [end]
    

    you probably don't want to capture:

     Data i want [End] Data
    

提交回复
热议问题