1

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.

Felipe
  • 256
  • 1
  • 8

1 Answers1

1

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
zx81
  • 41,100
  • 9
  • 89
  • 105