Search code examples
regexnano

Why does (?:\s)\w{2}(?:\s) not match only a 2 letter sub string with spaces around it not the spaces as well?


I am trying to make a regex that matches all sub strings under or equal to 2 characters with a space on ether side. What did I do wrong?

ex what I want to do is have it match %2 or q but not 123 and not the spaces.

update this \b\w{2}\b if it also matched one letter sub strings and did not ignore special characters like - or #.


Solution

  • You should use

    (^|\s)\S{1,2}(?=\s)
    

    Since you cannot use a look-behind, you can use a capture group and if you replace text, you can then restore the captured part with $1.

    See regex demo here

    Regex breakdown:

    • (^|\s) - Group 1 - either a start of string or a whitespace
    • \S{1,2} - 1 or 2 non-whitespace characters
    • (?=\s) - check if after 1 or 2 non-whitespace characters we have a whitespace. If not, fail.