Objective C - Trim spaces from end of each line of a string - ios

I have a string like this:
NSString* text = #" Line 1 \n Line 2 \n Line 3 ";
and I have to trim only the spaces of the end of each line, like this:
text = #" Line 1\n Line 2\n Line 3";
How can I do this using regular expression?
This question is not duplicated because the other posts removes only the spaces at the end of the string, not at the end of each line of the same string, and it is using regex.

Use this simple regex: (?m) +$
Sample Code
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"(?m) +$" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *result = [regex stringByReplacingMatchesInString:subject options:0 range:NSMakeRange(0, [subject length]) withTemplate:#""];
Explanation
(?m) turns on multi-line mode, allowing ^ and $ to match on each line
+ matches one or more space characters
The $ anchor asserts that we are at the end of the string

Related

How to replace strings using regex in objective C?

I have a string that sometimes contains strings like: #"[id123123|Some Name]"
What I have to do, is to simply replace it to "Some Name"
For example I have string: Some text lalala blabla [id123|Some Name] bla bla bla
And I need to get: Some text lalala blabla Some Name bla bla bla
The question is how to? My mind tells me that I can do this with NSRegularExpression
Look into stringByReplacingOccurrencesOfString:withString:options:range:. The options: allow the search string to be a regular expression pattern.
Not an Objective C person, but judging from this previous SO post, you could use a regex like so:
NSString *regexToReplaceRawLinks = #"\\[.+?\\|(.+?)\\]";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexToReplaceRawLinks
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *string = #"[id123|Some Name]";
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#"$1"];
This should match the string you are using and place the name in a group. You then replace the entire string [id123|Some Name] with Some Name.
Regex101
(\[[^|]+|([^\]]+]))
Description
\[ matches the character [ literally
[^|]+ match a single character not present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
| the literal character |
\| matches the character | literally
1st Capturing group ([^\]]+])
[^\]]+ match a single character not present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\] matches the character ] literally
] matches the character ] literally
In capture group 1 is the thing you want to replace with what is in capture group 2. enjoy.

iOS - NSString regex match

I have a string for example:
NSString *str = #"Strängnäs"
Then I use a method for replace scandinavian letters with *, so it would be:
NSString *strReplaced = #"Str*ngn*s"
I need a function to match str with strReplaced. In other words, the * should be treated as any character ( * should match with any character).
How can I achieve this?
Strängnäs should be equal to Str*ngn*s
EDIT:
Maybe I wasn't clear enough. I want * to be treated as any character. So when doing [#"Strängnäs" isEqualToString:#"Str*ngn*s"] it should return YES
I think the following regex pattern will match all non-ASCII text considering that Scandinavian letters are not ASCII:
[^ -~]
Treat each line separately to avoid matching the newline character and replace the matches with *.
Demo: https://regex101.com/r/dI6zN5/1
Edit:
Here's an optimized pattern based on the above one:
[^\000-~]
Demo: https://regex101.com/r/lO0bE9/1
Edit 1: As per your comment, you need a UDF (User defined function) that:
takes in the Scandinavian string
converts all of its Scandinavian letters to *
takes in the string with the asterisks
compares the two strings
return True if the two strings match, else false.
You can then use the UDF like CompareString(ScanStr,AsteriskStr).
I have created a code example using the regex posted by JLILI Amen
Code
NSString *string = #"Strängnäs";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[^ -~]" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#"*"];
NSLog(#"%#", modifiedString);
Output
Str*ngn*s
Not sure exactly what you are after, but maybe this will help.
The regular expression pattern which matches anything is. (dot), so you can create a pattern from your strReplaced by replacing the *'s with .'s:
NSString *pattern = [strReplaced stringByReplacingOccurencesOfString:#"*" withString:"."];
Now using NSRegularExpression you can construct a regular expression from pattern and then see if str matches it - see the documentation for the required methods.

How can i trim a blank(empty) line in NSString?

I have textView where user can add text in new line. but when user enter multiple new line and not enter a any text then i want skip all that line and just use only one new line.
I have String like below.
Hello,
How r u?
I want a string like this
Hello
How r u?
I have tried this but not working
strContects=[strContects stringByReplacingOccurrencesOfString:#"\n\n" withString:#"\n"];
How can i do this?
Hope u will understand?
You can replace multiple occurrence of omit multiple newline characters with single one by following regular expressions code
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\n+" options:0 error:NULL];
NSString *newString = [regex stringByReplacingMatchesInString:myString options:0 range:NSMakeRange(0, [myString length]) withTemplate:#"\n"];
this will print
Hello,
How r u? //in new line(all \n omitted with single \n)
If the goal here is removing all blank lines - not just consolidating multiple newlines - then it is worth noting the accepted answer wont remove an initial blank line in the string; eg "\nHello..."
A bit more involved, but try this category:
- (NSString*)stringByRemovingBlankLines
{
NSScanner *scan = [NSScanner scannerWithString:self];
NSMutableString *string = NSMutableString.new;
while (!scan.isAtEnd) {
[scan scanCharactersFromSet:NSCharacterSet.newlineCharacterSet intoString:NULL];
NSString *line = nil;
[scan scanUpToCharactersFromSet:NSCharacterSet.newlineCharacterSet intoString:&line];
if (line) [string appendFormat:#"%#\n",line];
}
if (string.length) [string deleteCharactersInRange:(NSRange){string.length-1,1}]; // drop last '\n'
return string;
}
(BTW - this can also handle other types of 'newline' characters which the accepted answer does not. This wasn't asked for, but it came up in the comments)

Remove multiple newlines/carriage-returns from a string

I'm trying to remove multiple newlines/carriage-returns from a string that may appear in any pattern (the strings come from social network APIs - TW, FB, YT). I was able to remove almost all combinations however I can't seem to remove multiple repetitions of "\r\n" or "\n\r".
What I would like is to have:
"Line1\r\nLine2\n\n\n\n\n\n\n\nLine3\r\r\r\r\rLine4\r\n\"Line5\"\n\r\n\rLine6\rLine7\r\n\r\nLine8\r\r\r\r\r\r\r\r\n\n\n\rLine9\n\n\n\n\n\r\r\r\r\nLine10\nLine11\n\n\n\n"
become:
Line1
Line2
Line3
Line4
"Line5"
Line6
Line7
Line8
Line9
Line10
Line11
but currently I get:
Line1
Line2
Line3
Line4
"Line5"
Line6
Line7
Line8
Line9
Line10
Line11
This is the code I have:
NSMutableString *testString = [[NSMutableString alloc]init];
[testString appendString:#"Line1\r\nLine2\n\n\n\n\n\n\n\nLine3\r\r\r\r\rLine4\r\n\"Line5\"\n\r\n\rLine6\rLine7\r\n\r\nLine8\r\r\r\r\r\r\r\r\n\n\n\rLine9\n\n\n\n\n\r\r\r\r\nLine10\nLine11\n\n\n\n"];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"(\r+)(\\n+)?(\r+)?|(\\n+)(\r+)?(\\n+)?|(\\n\r+)|(\r\\n+)" options:NSRegularExpressionCaseInsensitive error:nil];
[regex replaceMatchesInString:testString options:0 range:NSMakeRange(0, [testString length]) withTemplate:#"\n"];
I tried this out on a regex validation site and it works -> (\\r|\\n)+ or if you don't need to capture (?:\\r|\\n)+ Well it will be a varying number of slashes depending on whether or not they are actual carriage returns or just \r and \n (Plus you need to double the number of slashes for putting them inside an NSString literal)

How do I do backreferences correctly in Objective-C with NSRegularExpression?

In PHP I'd do something like this:
But in Objective-C, I tried this:
regex = [NSRegularExpression regularExpressionWithPattern:#"\\.([a-zA-Z0-9])" options:NSRegularExpressionCaseInsensitive error:&error];
result = [regex stringByReplacingMatchesInString:result options:0 range:NSMakeRange(0, [result length]) withTemplate:#". \1"];
But it ends up simply removing the first letter of the next sentence (such as "end. Chris" -> "end. hris"). Why is this?
Use $1, $2, etc. instead of \1, \2, etc. for back references.
See the docs for NSRegularExpression. Look under the "Template Matching Format" section.

Resources