Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如果连续存在两个以上的空格,则删除字符串中的空格_Regex_String - Fatal编程技术网

Regex 如果连续存在两个以上的空格,则删除字符串中的空格

Regex 如果连续存在两个以上的空格,则删除字符串中的空格,regex,string,Regex,String,假设我有这样的绳子 String sample = "This is a sample string with more than two spaces in a string "; 现在我要做的是使字符串在每个单词之间只有一个空格。 提前感谢。如果字面意思是“空格”,那么您可以用单个空格替换/{2,}/。请注意,正则表达式中的空格与文本中的空格匹配 如果“空格”实际上指的是“所有空格”(空格、制表符、换行符等),那么请使用\s+。将它们与\s+正则表达式匹配并替换为

假设我有这样的绳子

String sample = "This is a sample  string    with more than   two spaces in      a string   ";
现在我要做的是使字符串在每个单词之间只有一个空格。 提前感谢。

如果字面意思是“空格”,那么您可以用单个空格替换
/{2,}/
。请注意,正则表达式中的空格与文本中的空格匹配


如果“空格”实际上指的是“所有空格”(空格、制表符、换行符等),那么请使用
\s+

将它们与
\s+
正则表达式匹配并替换为单个空格。。 如果您只想替换多个空格(而不是制表符和其他白色字符),请使用
\+

如果这是C#,那么您可以这样做

using System.Text.RegularExpressions;
…
      String sample = "This is a sample  string    with more than   two spaces in      a string   ";
      sample = Regex.Replace(sample, @"\s+", " ");
可能重复的