Search code examples
regexregex-lookaroundslookbehindregex-look-ahead

How to select a specific character in regex if it match certain conditions


I'm trying to find a dash - from a string if it match certain conditions and only the dash should be selected by regex.

Cases it should be selected -

  1. If both sides has space. Example: test - dash
  2. If right hand side has space. Example: test- dash
  3. If both sides don't have space. Example: test-dash

Cases that it shouldn't be selected

  1. If there's no space on right side, but there's space on left side. Example: test -dash

Here's my progress

enter image description here

as the screenshot shows, I can achieve with positive-lookbehind, but this is not widely supported.

So, my question is, is there an alternative way to achieve this without using positive-lookbehind?

Thanks.


Solution

  • For the example data, if you can not use a lookbehind perhaps it might suffice to use a word boundary.

    -(?=\s)|\b-(?=[^\s-])
    

    Explanation

    • -(?=\s) Match - and assert a whitespace char to the right
    • | Or
    • \b-(?=[^\s-]) Word boundary, match - and assert at the right a non whitespace char except -

    Regex demo