0

I have below as string

name : abc,
position : 2

I want to make replace so that the string becomes as below

name : "abc",
position : 2

What change I want to do is abc will have double quotes so abc becomes "abc".

Note: abc is dynamic, it can be anything as below.

name : Test,
position : 2

name : Great,
position : 2

name : developers,
position : 2

Any idea how this can be done?

8
  • Your requirements are not that clear. Check this demo for Case 1. With the second case, isn't it a simple string replacement candidate? Commented Jan 11, 2017 at 7:49
  • explain a bit Anything can be anything? Commented Jan 11, 2017 at 7:53
  • okay, then what are great, test, developers here they must be an object? Commented Jan 11, 2017 at 8:03
  • @vaibhav : no, its a string... Commented Jan 11, 2017 at 8:09
  • So, there is no need to remove the comma now? Commented Jan 11, 2017 at 8:12

1 Answer 1

2

I suggest using \\b(name\\s*:\\s*)(.+), pattern and replace with $1"$2",:

NSError *error = nil;
NSString *myText = @"name : abc,\nposition : 2";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b(name\\s*:\\s*)(.+)," options:nil error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate:@"$1\"$2\","];
NSLog(@"%@", modifiedString);

See the Objective-C demo

Details:

  • \\b - a leading word boundary
  • (name\\s*:\\s*) - Group 1 matching name, 0+ whitespaces, : and 0+ whitespaces again
  • (.+) - any 0+ chars other than line break chars as many as possible
  • , - comma

The replacement pattern - $1"$2", - inserts Group 1 contents, ", Group 2 contents and ",.

See the regex demo.

Sign up to request clarification or add additional context in comments.

5 Comments

Its not working for first name if string is \t\tThis is test \t\tname : abc,\nposition : 2\n\nname : xyz,\nposition : 3\n\nname : jkl,\nposition : 3. Can you please look into this?
Replace (?m)^ with \\b
Perfect... Will let you know if there is anything else... Thanks a Ton!!!
\\b(name\\s*:\\s*)([a-zA-Z]+)\\s*, should work more better. Right? Here: regex
Just suit yourself, only you know the exact type of data coming in. If there can only be ASCII letters after name: and there may be optional whitespaces before a ,, yes, it will be better. .+ just matches the whole rest of the line. You might also want to check if \\b(name\\s*:\\s*)(.*\\S)\\s*, works "better" if there can be literally anything (but at least 1 non-whitespace) up to optional whitespace and ,. Mind that \s matches a newline, so, if you want to stay within 1 line, replace \\s with [\\p{Zs}\t] or [^\\S\r\n].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.