Johno Cown
Johno Cown

Reputation: 29

Regex: Capture everything up until a character sequence & if that character sequence doesn't exist, capture entire text

Aim:
Capture everything up until a character sequence & if those character sequences don't exist, capture entire text.

Character sequences: | table & | stats

Ex 1: search foo bar | table _time Action Direction returns search foo bar

Ex 2: search foo bar hello hi ciao 1234 returns search foo bar hello hi ciao 1234

Ex 3:
search foo bar
bar foo
| table _time Action Direction
returns
search foo bar
bar foo


Current solution which doesn't satisfy Ex 2:

(?<var>(?s).+?(?=\Q| table\E|\Q| stats\E))


You can use https://regex101.com/ for testing.
Any help would be very appreciated! Thank you.

Upvotes: 2

Views: 976

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You can use

(?s)^(?<var>.*?(?=\| (?:table|stats)|$))

See the regex demo.

Details:

  • (?s) - singleline/dotall modifier on
  • ^ - start of string
  • (?<var>.*?(?=\| (?:table|stats)|$)) - Group "var":
    • .*? - zero or more chars, as few as possible, up to the leftmost occurrence of
    • (?=\| (?:table|stats)|$) - either |+space+table or stats, or end of string.

Upvotes: 1

Related Questions