1

in this string: "TESTING (hello) 123 (HOW ARE YOU)"

I would like to match:

TESTING
123

Please help.. thanks!

I am only able to use (\\\(.*?\)) to match \(hello) and \(HOW ARE YOU), how can i match the counterpart of this strings?

5
  • So you actually have let s = "TESTING \\(hello) 123 \\(HOW ARE YOU)" as input, right? Commented Jun 6, 2019 at 9:28
  • Try [^\\()]+(?=\\\()|(?<=\))[^\\()]+? Commented Jun 6, 2019 at 9:35
  • @WiktorStribiżew Yeah Commented Jun 6, 2019 at 9:39
  • @Sweeper omg that works! Thank you so so so much!! :) Commented Jun 6, 2019 at 9:40
  • @maymaymaymaymay See Wiktor Stribiżew's solution. It's much faster than mine. Commented Jun 6, 2019 at 9:43

1 Answer 1

1

There is no way with ICU (the regex library used in Swift) regex to match a text chunk that is not equal to some multicharacter string. You could do it if you wanted to match any 1 or more chars other than some specific character. You can't do it if you are "negating" a whole sequence of chars.

You may use

let str = "TESTING \\(hello) 123 \\(HOW ARE YOU)"
let pattern = "\\s*\\\\\\([^()]*\\)\\s*"
let result = str.replacingOccurrences(of: pattern, with: "\0", options: .regularExpression)
print(result.components(separatedBy: "\0").filter({ $0 != ""}))

Output: ["TESTING", "123"]

The idea is to match what you do not need and replace them with a null char, and then split the string with that null char.

Pattern details

  • \s* - 0+ whitespaces
  • \\\( - a \( substring
  • [^()]* - 0+ chars other than ( and )
  • \) - a ) char
  • \s* - 0+ whitespaces.

The results are likely to contain empty strings, hence .filter({ $0 != ""}) is used to filter them out.

Sign up to request clarification or add additional context in comments.

3 Comments

What if i have two strings: a = "HELLO HOW ARE YOU" b = "TESTING \\(hello) 123 \\(HOW ARE YOU)" is it possible to have a regex that matches "HELLO HOW ARE YOU" in a and "TESTING", "123" in b?
@maymaymaymaymay For your a string, the result is ["HELLO HOW ARE YOU"]. For the b string, I get ["TESTING", "123"]. Just what you ask for.
@maymaymaymaymay To clear it out for you: there is no way with ICU regex to match a text chunk that is not equal to some multicharacter string. You could do it if you wanted to match any 1 or more chars other than some specific character. You can't do it if you are "negating" a whole sequence of chars.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.