Home > Software design >  Regex - capture character before pattern until a specific character
Regex - capture character before pattern until a specific character

Time:02-12

I'm trying to match h.Z.getAssetUrl("/FullLogo.svg") from the following string

4H18V5.2H2z"})),t)})),p=t(7103),h=t(1313),m=function(){return(0,o.jsx)(a.Ee,{src:`h.Z.getAssetUrl("/FullLogo.svg")`,width:"195px",height:"36px"})},g=function(e){var r=e.toggle,t=e.isOpen;return(0,o.jsx)(i.xu,{display:{base:"block",md:"none"}

I've tried /getAssetUrl\(. ?\)/, this matches getAssetUrl("/FullLogo.svg"). How do I also match the h.Z. before it. I want to match ahead until a : is encounterd.

CodePudding user response:

You can match all but : chars before your pattern:

/[^:]*getAssetUrl\([^()]*\)/

I also suggest using a negated character class to match a string between two parentheses.

Details:

  • [^:]* - zero or more chars other than :
  • getAssetUrl\( - a getAssetUrl( string
  • [^()]* - zero or more chars other than ( and ) chars
  • \) - a ) char.

See the regex demo.

CodePudding user response:

With your shown samples, please try following regex. Here is the Online demo for following regex.

^.*?:\K(?:.*?\.){2}(?:.*?"){2}\)

Explanation: Adding detailed explanation for above.

^.*?:         ##From starting of value matching till very first occurrence of : using lazy match here.
\K            ##Forget previous match by \K option till here so that we can print only required output.
(?:           ##Opening a non-capturing group here.
  .*?\.       ##Matching till dot by doing a lazy match here.
){2}          ##Match 2 occurrence of lazy matches(means match till 2 dots only).
(?:.*?"){2}\) ##In a non-capturing group matching till " as a lazy match and by mentioning {2} means perform two matches of it followed by a \ to get needed value.
  • Related