Home > Back-end >  regex if then pattern match
regex if then pattern match

Time:01-05

I have a page title string that I want to grab a substring (the Brand Name) from, however it doesn't appear in the same spot all the time.

Page Title:

  • Brand Name A | Book now
  • Brand Name B | Order here
  • Content | Brand Name A | Order now
  • Content | Brand Name 7 | Click here

Desired output:

  • Brand Name A
  • Brand Name B
  • Brand Name A
  • Brand Name 7

I can get the Brand Name from the first two using (^[^|] ) and grab the Brand Name from the second two with \|(.*).*(?=\|) - although it grabs the | as well.

However, I need the first regex to apply when there is 1 pipe and the second regex to apply when there are 2 pipes. Any suggestions?

CodePudding user response:

Using REGEXP_EXTRACT we can try:

REGEXP_EXTRACT("Content | Brand Name A | Order now", "\\s*([^|] ?)\\s \\|[^|] $")

Here is a regex demo.

  •  Tags:  
  • Related