You can make use of lookaround in regex here
(?<!&)&(?!&)
The above regex matches an &
neither preceded nor followed by another &
.
Question
Can you please suggest me regular expression which will only match '&' from string but not '&&'.
E.g. Input String
s1 = "STRING1 && STRING2 & STRING3 AND STRING4";
I'm splitting input string with function -
String[] param = s1.split('&'); or s1.split('&(?!&&)');
Result after split should be -
param[1] = STRING1 && STRING2
param[2] = STRING3 AND STRING4
Thank you for your replies.
Dev
Solution
You can make use of lookaround in regex here
(?<!&)&(?!&)
The above regex matches an &
neither preceded nor followed by another &
.
OTHER TIPS
You can use this pattern as well:
[^&]&[^&]
and a call to some language specific SPLIT
function should do the job.
If this is for iOS platform, try this example in a separate app:
NSString *string = @"STRING1 && STRING2 & STRING3 AND STRING4"; //[NSString stringWithFormat:@"%@", @""];
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^&]&[^&]"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:string
options:0
range:NSMakeRange(0, [string length])];
NSLog(@"numberOfMatches : %d", numberOfMatches);
NSArray *matches = [regex matchesInString:string
options:0
range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) // adjust loop per your criteria
{
NSRange matchRange = [match range];
// Pick the separator
NSLog(@"::::%@", [string substringWithRange:matchRange]);
// Splitted string array
NSArray *arr = [string componentsSeparatedByString:[string substringWithRange:matchRange]];
NSLog(@"Splitted String : %@", arr);
}
It may not be elegant but i would replace the isolated & for something else and then i would do the split.
Something like this (pseudo code, not IOS Syntax):
// s1 = "STRING1 && STRING2 & STRING3 AND STRING4";
aux=s1.replaceAll("([^&])&([^&])","$1 _SEPARATOR_ $2");
// in case of & at the beginning
aux=aux.replaceAll("^&([^&])"," _SEPARATOR_ $2");
// in case of & at the end
aux=aux.replaceAll("([^&])&$","$1 _SEPARATOR_ ");
// now aux="STRING1 && STRING2 _SEPARATOR_ STRING3 AND STRING4";
String[] params=aux.split(" _SEPARATOR_ ");