Regular Expressions to find a string included between two symbols while EXCLUDING the preceding / ending space

Viewed 56

I need to extract from a string a set of characters (TEXT1 / TEXT2 / TEXT3) which are included between two delimiters, without returning the delimiters themselves, nor the preceding or ending spaces.

My strings look like this:

  1. TEXT1 | characters
  2. digits.digits - TEXT2 | characters
  3. characters - digits digits-digits-digits - TEXT3 | characters
  4. characters - digits digits/digits/digits - TEXT4 | characters

Is it possible to write a single regex that would work to extract TEXT1 / TEXT2 / TEXT3 / TEXT4 for all strings above?

And what if my string looks like this?

  1. Lorem Ipsum dolor/sit | LOT53 - Tc
  2. 80.LT79 - Lorem Ipsum Amet | LOT25 - Ar
  3. CT1: asda acar - 12 09-13-2022 - Lorem Ipsum dolor/sit | LOT54 - Ca
  4. 52.85 Cat - 9/17/2021 - Lorem, Ipsum & Dolor | LOT12 - Ps

I need a single regex to extract what is bold.

2 Answers
[^\d-]*(\w+)\s?(?=\|)

[^\d-]* match all but digits and "-"

(\w+) match words

\s? match whitespace or not

(?=\|) lookahead "|"

you can also tinker it here

You can use (?:-\h+)?(\w+)\h+\|.

Demo


Based on your edit, you can use the single regex:

(?:(?:-\h+)?([a-zA-Z]+\d+)\h+\|)|(\|\h+([a-zA-Z]+\d+))

to get tagged words of either form. You just need to figure out group 1 or group 2 programmatically after the match.

Demo

Related