需要C#正则表达式替换字符串里的空格 [英] Need C# Regex for replacing spaces inside of strings

查看:1169
本文介绍了需要C#正则表达式替换字符串里的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#,我需要一些代码来使用正则表达式用引号字符(|)替换引号内的空格。问题是字符串可能包含多个带引号的表达式,而 我只想要引号内 的空格。

Using C#, I need a some code to use regular expressions to replace spaces inside of quotes with a pipe character (|). problem is that the string could contain multiple quoted expressions and I only want the spaces inside of quotes.

尝试了几件事,但我正在努力处理可变内的可变数字的话,除了别的以外。

I tried a few things but I am struggling with how to handle the variable number of words that could be inside of quotes, amongst other things.

这里有一些例子,输入和所需输出:

Here is some examples of what may be input, and the required output:

word1 word2

- >word1 | word2

"word1 word2"
-> "word1|word2"

word1 word2word3word4 word5

- >word1 | word2word3word4 | word5

"word1 word2" word3 "word4 word5"
-> "word1|word2" word3 "word4|word5"

word1word2 word3

- > word1word2 | word3

word1 "word2 word3"
-> word1 "word2|word3"

任何帮助非常感谢,希望我将了解正则表达式。 / p>

Any help greatly appreciated, and hopefully I will learn about regular expressions.

推荐答案

使用常规expresion查找引号,并使用替换替换空格:

Use a regular expresion to find the quotes, and a plain Replace to replace the spaces:

str = Regex.Replace(str, @"""[^""]+""", m => m.Value.Replace(' ', '|'));

这篇关于需要C#正则表达式替换字符串里的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆