Reputation: 21571
For some reason I cannot make regular expressions work for multiline string. It works fine on a web
I have a text like this:
First Line //remove leading spaces
Second Line //nothing to remove
Third Line //remove leading spaces
Fourth Line
should be 1 line //remove leading spaces and new line next char is not a capital letter
Fifth line //remove leading spaces, keep new line between the two sentences
I'm trying to use this regex
^ +|\b\n\b
It works almost fine (except it removes more new line than needed) in online regex editors such as http://rubular.com/r/u4Ao5oqeBi
But it only removes the leading spaces from the first line This is my code:
NSString *myText = @" First Line (remove leading spaces\nSecond Line (nothing to remove\n Third Line (remove leading spaces\n Fourth Line\nshould be 1 line (remove leading spaces and new line next char is not a capital letter\n\n Fifth line (remove leading spaces, keep new line between the two sentences";
NSLog(myText);
NSString *resultText = [myText stringByReplacingOccurrencesOfString: @"^ +|\\b\\n\\b"
withString: @""
options: NSRegularExpressionSearch
range: NSMakeRange(0, myText.length)];
NSLog(resultText);
Upvotes: 0
Views: 80
Reputation: 626845
Your code does not work because you are using stringByReplacingOccurrencesOfString
with a regex string in the target
argument instead of the input string. It does not accept regular expressions. See the Foundation Framework Reference help on this function.
You can use the following code to remove all leading spaces:
NSError *error = nil;
NSString *myText = @" First Line (remove leading spaces\nSecond Line (nothing to remove\n Third Line (remove leading spaces\n Fourth Line\nshould be 1 line (remove leading spaces and new line next char is not a capital letter\n\n Fifth line (remove leading spaces, keep new line between the two sentences";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^ +" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate:@""];
NSLog(@"%@", modifiedString);
I am using NSRegularExpressionAnchorsMatchLines
option to make ^
match the beginning of a line, not the beginning of the entire string (see this Regular Expressions Metacharacters table).
Output:
First Line (remove leading spaces
Second Line (nothing to remove
Third Line (remove leading spaces
Fourth Line
should be 1 line (remove leading spaces and new line next char is not a capital letter
Fifth line (remove leading spaces, keep new line between the two sentences
Upvotes: 1