Home > database >  Regexp - Get everything before two different strings. One can contain both
Regexp - Get everything before two different strings. One can contain both

Time:07-13

I have to use regexp.

Current state: . ?((/=\.czxy)|(?=\.zzzz))

It's working for the first two cases (that's obvious)

So I have decided to do something like this: . ?((/=\.czxy)|(?=\.zzzz)|(?=\-\-[0-9]))

But this still doesn't work. (There is OR).

I want to have everything before the extension. (Example 1 and 2) When string is ended with '--1,--2, --3... and so on', I need to have everything before that. (Example 3 and 4)

Note: I cannot use if construction.

Examples:

  • 123_abc_cb1.czxy -> 123_abc_cb1
  • 123_23c_cb1.zzzz -> 123_23c_cb1
  • 123_abc_cb1--1.czxy -> 123_abc_cb1
  • 123_23c_cb1--1.zzzz -> 123_23c_cb1

EDIT: 123_abc_cb1 is a random combination of letters, numbers and special characters, there can be everything.

CodePudding user response:

You don't need any lookarounds if you can use a capture group. To match characters and underscore you can use for example \w to match word characters:

(\w )(?:--\d )?\.(?:czxy|zzzz)\b

Regex demo

CodePudding user response:

Your attempt has these issues:

  • A typo: (/= should be (?=
  • The regex does not require that the --[0-9] part is still followed by the extension. That part should actually be an optional part that precedes the pattern for the extension.

So change to this:

^. ?(?=(?:--\d)?\.(?:czxy|zzzz))

Or -- if matches do not necessarily start at the start of the input/line:

(?<!\S). ?(?=(?:--\d)?\.(?:czxy|zzzz))

CodePudding user response:

why not use the recurrent information "_cb1"

/.*_cb1/
  • Related