0

I have a scenario where i want to extract the string within bracket after each selected string

  1. PS=AV_2
  2. PS=AV_2(AA)
  3. PS=AV_2(AA),PS=AV_20(BB,ZZ)
  4. PS=AV_2,PS=AV_20
  5. PS=AV_2(ZZ),PS=AV_20

eg. input will be PS=AV_2(AA),PS=AV_20(BB,ZZ) and selectedQues = AV_20 or AV_2 In above only constant part is "PS=" all other string can be anything and any format.

The function should return the string in bracket.

func getStringList(input: String, selectedQues: String ) -> [String] {

       // let pattern = "/\\((.*)\\)/"  //1. "/\(([^)]+)\)/"   //2. "/\\(([^)]+)\\)/)"  //3. "([\\w]+(?:,[\\w]+))" some tried regular expression
        let pattern = "/\(selectedQues)\\(([^)]+)\\)/g"
        let nsString = input as NSString
        let regExp = try! NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
        let results = regExp.matchesInString(input, options: [], range:NSMakeRange(0, nsString.length))

        return results.map { nsString.substringWithRange($0.range)}
}

I am unable to resolve a regular expression for the same. I would be really grateful if someone can help or point to some help.

9
  • You cannot use regex delimiters in Swift regex. Try let pattern = "\(selectedQues)\\(([^)]+)\\)" Commented Feb 2, 2016 at 11:36
  • BTW, you can use the code to access Group 1 text from this answer. Commented Feb 2, 2016 at 11:48
  • removing the delimiter did not resolved the issue. Commented Feb 2, 2016 at 11:51
  • Did you check your code with the one in my previous answer? In your code, you are not accessing the captured text, you only try to access the matches. Commented Feb 2, 2016 at 11:54
  • For PS=AV_2(AA) it is returning me AV_2(AA) but i expect only AA to be returned by function. Also for PS=AV_2(AA),PS=AV_20(BB,ZZ) the app is crashing Commented Feb 2, 2016 at 12:44

0

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.