How to surround words with quotes
How to surround words with quotes Ex. Unite开发者_StackOverflow社区d states, US, with 'United states', 'US',
In your case
resultString = Regex.Replace(subjectString, @"\b[^,]+\b", "'$0'");
would work, but you might want to define your requirements a little more clearly.
EDIT:
Now that you've clarified that your string is always divided into two parts (Name and Country Code), this might be better:
resultString = Regex.Replace(subjectString, @"^(.+),\s*([^,]+)$", "'$1', '$2'", RegexOptions.Multiline);
This will change the multiline string
United States, US
Switzerland, CH
BOLIVIA, PLURINATIONAL STATE OF, BO
into
'United States', 'US'
'Switzerland', 'CH'
'BOLIVIA, PLURINATIONAL STATE OF', 'BO'
(but also works if you apply it to one line at a time).
var quoted = myString.Replace("US", "'US'").Replace("United States", "'United States'");
No need for regex for a simple task.
Here's a simple solution, using string manipulation:
string s = "BOLIVIA, PLURINATIONAL STATE OF, BO";
Wrap with single quotes:
int lastComma = s.LastIndexOf(", ");
s = String.Format("'{0}', '{1}'", s.Remove(lastComma), s.Substring(lastComma + 2));
If you always have 2 letters at the end of the string, you can simplify it even further:
int lastComma = s.Length - 4;
You probably want some error checking, but this looks like a very simple task, that doesn't require anything as fancy as a regular expression.
精彩评论