Return a regex match in a Bash script, instead of replacing it

前端 未结 9 784
面向向阳花
面向向阳花 2021-01-31 04:30

I just want to match some text in a Bash script. I\'ve tried using sed but I can\'t seem to make it just output the match instead of replacing it with something.



        
9条回答
  •  心在旅途
    2021-01-31 04:58

    I Know this is an old topic but I came her along same searches and found another great possibility apply a regex on a String/Variable using grep:

    # Simple
    $(echo "TestT100String" | grep -Po "[0-9]{3}")
    # More complex using lookaround
    $(echo "TestT100String" | grep -Po "(?i)TestT\K[0-9]{3}(?=String)")
    

    With using lookaround capabilities search expressions can be extended for better matching. Where (?i) indicates the Pattern before the searched Pattern (lookahead), \K indicates the actual search pattern and (?=) contains the pattern after the search (lookbehind).

    https://www.regular-expressions.info/lookaround.html

    The given example matches the same as the PCRE regex TestT([0-9]{3})String

提交回复
热议问题