我有一个字符串如下;
dim str as string = "this is a string . "
我想识别那些多个空格字符并用一个空格字符替换。使用替换函数将替换所有这些,那么执行此类任务的正确方法是什么?
答案 0 :(得分:2)
import System.Text.RegularExpressions
dim str as string = "This is a test ."
dim r as RegEx = new Regex("[ ]+")
str = r.Replace(str, " ")
答案 1 :(得分:2)
使用Regex类匹配“一个或多个空格”的模式,然后用一个空格替换所有这些实例。
以下是执行此操作的C#代码:
Regex regex = new Regex(" +");
string oldString = "this is a string . ";
string newString = regex.Replace(oldString, " ");
答案 2 :(得分:1)
我会使用更容易阅读的\ s +修饰符
public Regex MyRegex = new Regex(
"\\s+",
RegexOptions.Multiline
| RegexOptions.CultureInvariant
| RegexOptions.Compiled
);
// This is the replacement string
public string MyRegexReplace = " ";
string result = MyRegex.Replace(InputText,MyRegexReplace);
或者在VB中
Public Dim MyRegex As Regex = New Regex( _
"\s+", _
RegexOptions.Multiline _
Or RegexOptions.CultureInvariant _
Or RegexOptions.Compiled _
)
Public Dim MyRegexReplace As String = " "
Dim result As String = MyRegex.Replace(InputText,MyRegexReplace)
答案 3 :(得分:0)
使用正则表达式。正如其他SO用户here