J. D.
J. D.

Reputation: 171

Regex to get everything before the first slash except between quotes

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

Upvotes: 4

Views: 86

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

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 '

Upvotes: 1

gtgaxiola
gtgaxiola

Reputation: 9331

How about:

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

See Regex Demo

Using Group 1

Upvotes: 0

Related Questions