简体   繁体   中英

REGEX Adding a string before comma c#

How can I append a known string before each coma on a comma separated string. Is there a regex for that or something that doesn't use a loop EX

given string :

email, email2, email3  (etc...)

to

string suffix = "@iou.com"
string desiredResult = "email@iou.com, email2@iou.com, email3@iou.com

Thank you!!

You can use [^,\\s]+ regexp, and replace with "$0"+suffix :

var res = Regex.Replace(original, @"[^,\s]+", "$0"+suffix);

"$0" refers to the content captured by the regular expression.

Demo.

Here you are:

string input = "email, email2, email3";
string suffix = "@iou.com";
//string desiredResult = "email@iou.com, email2@iou.com, email3@iou.com";
Console.WriteLine(Regex.Replace((input + ",")
    .Replace(",", suffix + ","), @",$", ""));

Hope this helps.

或使用LINQ:

Console.WriteLine(string.Join(",",input.Split(',').Select(s => string.Concat(s, suffix))));

You could use a zero-length capture group. Here's how that might look:

\w+(?<ReplaceMe>),?

The \\w matches alphanumeric characters, and the named capture group called "ReplaceMe" matches the zero-length space between the end of the word and the beginning of the comma (or any other non-alphanumeric item, including the end of the string).

Then you'd just replace ReplaceMe with the appended value, like this:

Regex.Replace(original, @"\w+(?<ReplaceMe>),?", "@email.com");

Here's an example ofthat regex in action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM