Search code examples
regexsublimetext

Regex match strings only after certain character


I want to remove all numbers, but only after |

blah, 1. retain 3. dont alter..blah | blah 1. remove balh.. 19. altered

after I apply regex the string should be

blah, 1. retain 3. dont alter..blah | blah remove balh..  altered

when I replace using this regex [0-9]+\. It matches all the "numbers with dot" even before | , and when I use regex | [0-9]+\. it only selects the first number and dot i.e 1., after |


Solution

  • You can assert not a pipe char to the right using a negative lookahead and using a negated character class ruling out a newline or |:

    \d+\.(?![^\r\n|]*\|)
    

    Explanation

    • \d+\. Match 1+ digits and a dot
    • (?! Negative lookahead, assert not to the right
      • [^\r\n|]*\| Match optional chars other than a newline or |
    • ) Close lookahead

    See a regex demo.


    Another option is to use a positive lookahead to assert not a pipe char to the right until the end of the string:

    \d+\.(?=[^\r\n|]*$)
    

    Explanation

    • \d+\. Match 1+ digits and a dot
    • (?= Positive lookahead, assert to the right
      • [^\r\n|]*$ Match optional chars other than a newline or | till end of string $
    • ) Close lookahead

    See a regex demo.