Skip to content
Advertisement

Need help to match regex with conditional concatenation (JS)

I need help to accomplish the use cases of this regex: https://regex101.com/r/HmDQHJ/3/

Right now, my issue is that I need to match this:

T("
test
'me'
")

But also fail on this:

T('fail me' 'fail me')

Can someone help me to accomplish this? Thank you!

More context:

We have an old crawler that goes project source and looks for usage of a function called “T”, then it should extract the string that is passed to this function.

This can be used like: T("Something with 'single quote' in it") or T('Something without single quote'), then it can have break lines after the T( or after T('|". I can’t really change much in this code right now aside from the regex, so thus I’m trying to do it with this approach.

Advertisement

Answer

This below pattern should work with all the test cases you have listed.

Pattern: T(n?(?:(?:'[^']+')|(?:"[^"]+"))n?)

Breakdown:

  • (?:'[^']+'): Match ' followed by any number of sequences of any char other than '
  • (?:"[^"]+"): Or do similar match with "

Demo: https://regex101.com/r/HmDQHJ/6/

Thanks

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement