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,241
  • 10
  • 22
  • 27
J. D.
  • 161
  • 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
  • 561,645
  • 34
  • 376
  • 476
0

How about:

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

See Regex Demo

Using Group 1

gtgaxiola
  • 9,059
  • 5
  • 43
  • 63