Search code examples
regexregex-negationregex-lookaroundsregex-groupregex-greedy

Restrict first and last characters to be whitespace


I want a regex to match something like _Hello_ or _Hell No_

So the requirements are _ on both sides and some text in between. However the text cannot start with or end with whitespace (they can however contain whitespace inside the text).

I have tried _[\S]+.*[\S]+_ but this fails to match when i have less than 2 characters in the text eg _H_

Please help


Solution

  • You can just treat the single-character case separately:

    _(\S.*\S|\S)_
    

    You probably want to replace .* with .*? to make it non-greedy. Otherwise, you'll fail to properly match multiple instances of this pattern in a row:

    _foo_ _bar_
     ^^^^^^^^^
     one match