I have a Regular Expression in Objective-C and I need to know how to get a certain variable…
I want to find a string that has the letter “a” somewhere in it followed by any number (including zero) of B’s, C’s, and D’s after it and at the first non-B,C,D I want to close my search statement. Then I want to replace the A with an F and add an F to the end of my search-string.
For example: “ZYXABCBBDBCBDEJKS” would search and return: “ZYXABCBBDBCBDEJKS” … so the string I am now working with is “ABCBBDBCBDE”, I want this string to turn into this string “FBCBBDBCBDEF” and then be put back into the original string… so the final returned string will be “ZYXFBCBBDBCBDEFJKS”
I’m new to RegEx but I gave it a shot with the below objective-c code and it didn’t work… I think this is because my variables on the second line of code (at the “withTemplate” part) are wrong… I shouldn’t use “$2” or “$1” should I?
code:
regex = [NSRegularExpression regularExpressionWithPattern:@"A(B|C|D)*([^B|C|D])"
options:0
error:nil];
modifiedString = [regex stringByReplacingMatchesInString:myString
options:0
range:NSMakeRange(0, [htmlstring length])
withTemplate:@"F$1$2F"];
In your regex –
(B|C|D)*will only capture the last matched character out of(B|C|D), since*is out of the captured group. Also, in a character class, you don’t need to use apipeto alternate, as you did in 3rd part. So, either you usecharacter class, or you usepipeto alternate in groups. And in this particular case, I would suggest to use character class in both place.So, you can try changing your regex to: