Home > Blockchain >  Regex: Match either of 2 groups, but not both
Regex: Match either of 2 groups, but not both

Time:10-02

I need to match a string that has either a prefix, or a suffix.

So far, I've done this:

(?i)(?:(?:Localized(?:App)?String\(@))?\"(. ?)\".(?:localized)?

Testing this regex against the scenario below, it works well, except for the first line, where I should have no matches:

print("Error: should NOT capture!")
NSLocalizedAppString(@"Contextual Menu",nil)];
self.setTitleStates(["Unmute1".localized, "Mute".localized])
NSApplication.localizedString("Paused", comment: "")
print("Remove from Set".localized)

How do I mutually exclude the prefix group with the suffix group?

Thanks!

CodePudding user response:

You can use

(?si)Localized(?:App)?String\(@?"([^"\\]*(?:\\.[^"\\]*)*)"|"([^"\\]*(?:\\.[^"\\]*)*)"\.localized

See the regex demo. Details:

  • (?si) - dot now matches line breaks and i makes the pattern case insensitive
  • Localized - a word
  • (?:App)? - an optional App string
  • String\( - a String( text
  • @? - an optional @
  • "([^"\\]*(?:\\.[^"\\]*)*)" - a "..." string literal pattern with escape sequences support
  • | - or
  • "([^"\\]*(?:\\.[^"\\]*)*)" - a "..." string literal pattern with escape sequences support
  • \.localized - .localized string.
  • Related