开发者

Regular expression .Net replace single characters followed by spaces at the beginning of string

开发者 https://www.devze.com 2022-12-24 19:18 出处:网络
I need to replace \"x y z word1 word2\" with \"x_y_z word1 word2\" The number of single characters may开发者_Python百科 vary.You can achieve that by abusing lookahed:

I need to replace "x y z word1 word2" with "x_y_z word1 word2"

The number of single characters may开发者_Python百科 vary.


You can achieve that by abusing lookahed:

Regex.Replace(str, @"(?<=^\w?(\s\w)*)\s(?=\w\s)", "_");

Finds spaces that are after a sequence of spaces and single letters, and before another such letter. Please note that that would not work on all Regex flavors, but .net handles it well.

Another option is using the MatchEvaluator:

Regex.Replace(str, @"^(\w )+",
              match => match.Value.TrimEnd().Replace(' ', '_') + " ");

In this version the regex is easy, but we do some post processing - the function removes the last space, and replaces all other spaces with underscores.


Regex.Replace(yourstring, "^x y z ", "x_y_z ")

would do it, of course. How much you want to generalize depends on exactly what "symbols followed by spaces" you want to replace (given that you don't want to replace word1 and later in your sample string); for example, if you want to replace exactly three single-character identifiers (followed by spaces) at the start of the string, the proper generalization is:

Regex.Replace(yourstring, "^([a-z]) ([a-z]) ([a-z]) ", "$1_$2_$3 ")

but it's different if you want to replace different numbers of identifiers, or identifiers of different lengths, etc, etc. Tell us exactly what you want to replace (and where you want to stop replacing) and we can be more specific in our suggestions.

0

精彩评论

暂无评论...
验证码 换一张
取 消