4

I am looking to create a Regex to extract everything before the first slash except if it is in single or double quotes. Currently, I have:

^(.*?)/

Now, I am at a lost. Based on the different texts below, I just want the bolded part below:

Text

abc,def,ghi,jkl,mno /123
/abc,def,ghi,jkl,mno 123
abc,/def,"/ghi",jkl,mno /123
abc,def,"/ghi",jkl,mno /123
abc,def,'/ghi',jkl,mno /123

L_J
  • 2,351
  • 10
  • 23
  • 28
J. D.
  • 171
  • 2
  • 13

2 Answers2

1

You may use

^(?:[^/"']|"[^"]*"|'[^']*')+

See the regex demo

Details

  • ^ - start of string
  • (?:[^/"']|"[^"]*"|'[^']*')+ - 1 or more occurrences of
    • [^/"'] - any char other than /, " and '
    • | - or
    • "[^"]*" - a ", any 0+ chars other than ", and then "
    • | - or
    • '[^']*' - a ', any 0+ chars other than ', and then '
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

How about:

^(.*?)\/(?=([^\"\']*\"[^\"\']*\")*[^\"\']*$)

See Regex Demo

Using Group 1

gtgaxiola
  • 9,241
  • 5
  • 42
  • 64