Search code examples
regexif-statementcasepcre

Case analysis with REGEX


I have some data like

small_animal/Mouse
BigAnimal:Elephant
Not an animal.

What I want to get is:

Mouse
Elephant
Not an animal.

Thus, I need a regular expression that searches for / or : as follows: If one of these is found, take the text behind that character. If neither / nor : exists, take the whole string.

I tried a lot. For example this will work for mouse and elephant, but not for the third line:

(?<=:)[^:]*|(?<=/)[^/]*

And this will always give the full string ...

(?<=:)[^:]*|(?<=/)[^/]*|^.*$

My head is burning^^ Maybe, somebody can help? :) Thanks a lot!

EDIT:

@The fourth bird offered a nice solution for single characters. But what if I want to search for strings like

animal::Dog
Another123Cat
Not an animal.

How can I split on :: or 123?


Solution

  • You might use

    ^(?:[^:/]*[:/])?\K.+
    
    • ^ Start of string
    • (?:[^:/]*[:/])? Optionally match any char except : or / till matching either : or /
    • \K Forget what is matched so far
    • .+ Match 1+ times any char

    regex demo

    If you don't want to cross a newline, you can extend the character class with [^:/\r\n]*

    Another option could be using an alternation

    ^[^:/]*[:/]\K.+|.+
    

    Regex demo

    Or perhaps making use of a SKIP FAIL approach by matching what you want to omit

    ^[^:/]*[:/](*SKIP)(*F)|.+
    

    Regex demo


    If you want to use multiple characters, you might also use

    ^(?:(?:(?!123|::|[:/]).)*+(?:123|::|[:/]))?\K.+
    

    Regex demo