Search code examples
regexregex-group

Regex-How to split string by delimiter and if there is no delimiter return whole


I would like to extract some information from a string like below:

ksdfXX2344_vvs_gfedfg
ksdfXX2344

For example, to extract word ksdfXX2344 from the string above.
Currently I have:

(.*?)(_.*)

which can extract the words in situation 1, but cannot extract the string with no delimiter _. How can I extract the words if there are no delimiter inside? Any suggestions?

Many thanks!


Solution

  • Don't split, replace:

    Search: '_.*'
    Replace: ''
    

    eg in java:

    String prefix = str.replaceAll("_.*", "");
    

    or python:

    prefix = re.sub(r'_.*', '', str)
    

    To match only the prefix:

    ^[^_]*
    

    this matches everything at the start that isn't an underscore, so the match will stop before the first underscore or end-of-input if there isn't an underscore.