VB.net 正则表达式--将多个连续空格替换为一个空格的正则表达式

时间:2022-11-11 15:39:08
Dim reg As Regex
        Dim striniData As String = "a   b     c       d"
        Dim sectionList As System.Text.RegularExpressions.MatchCollection

        Try
            '' Using regular expression to get all section names.
            reg = New Regex(":%s/*//g")
            sectionList = reg.Matches(striniData)
            MsgBox(sectionList.count)
        Catch ex As Exception
            Throw ex
        End Try

程序不报错,当没有结果。请指教一下。辛苦了。

8 个解决方案

#1


New Regex("[\x20 ]", g)

更多语法,推荐参考:
http://www.regexlab.com/zh/regref.htm

#2


New Regex("[\x20 ]", g)

能不能写个例子啊。我不是很明白,,辛苦了。

#3


reg = New Regex("[\x20 ]{2,}");
striniData = reg.Replace(striniData, " ");

--- 或者 ---

striniData = Regex.Replace(striniData, "[\x20 ]{2,}", " ");


正则表达式语法帮助,参见:
http://www.regexlab.com/zh/regref.htm

#4


简单点:
string_xx=string_xx.replace("       "," ")
string_xx=string_xx.replace("      "," ")
string_xx=string_xx.replace("    "," ")
string_xx=string_xx.replace("   "," ")
string_xx=string_xx.replace("  "," ")
.......

#5


我有个笨办法, 写个死循环,如果有两个空格就换成一个空格,直到不再有2个空格。那也就只剩下一个空格了。

#6


string msg="1 2 3  4 5   6"
msg=Regex.Replace (msg, " +"," ");
结果: 
msg=="1 2 3 4 5 6"

#7


sz_lgp(longguoping) 有点不智能,但这个方法很好
string_xx=string_xx.replace("       "," ")
string_xx=string_xx.replace("      "," ")
string_xx=string_xx.replace("    "," ")
string_xx=string_xx.replace("   "," ")
string_xx=string_xx.replace("  "," ")

#8


string msg="1 2 3  4 5   6"
msg=Regex.Replace (msg, " +"," ");
结果: 
msg=="1 2 3 4 5 6"
没测试,但是msg会不会 = “1+2+3++4+5+++6”啊

#1


New Regex("[\x20 ]", g)

更多语法,推荐参考:
http://www.regexlab.com/zh/regref.htm

#2


New Regex("[\x20 ]", g)

能不能写个例子啊。我不是很明白,,辛苦了。

#3


reg = New Regex("[\x20 ]{2,}");
striniData = reg.Replace(striniData, " ");

--- 或者 ---

striniData = Regex.Replace(striniData, "[\x20 ]{2,}", " ");


正则表达式语法帮助,参见:
http://www.regexlab.com/zh/regref.htm

#4


简单点:
string_xx=string_xx.replace("       "," ")
string_xx=string_xx.replace("      "," ")
string_xx=string_xx.replace("    "," ")
string_xx=string_xx.replace("   "," ")
string_xx=string_xx.replace("  "," ")
.......

#5


我有个笨办法, 写个死循环,如果有两个空格就换成一个空格,直到不再有2个空格。那也就只剩下一个空格了。

#6


string msg="1 2 3  4 5   6"
msg=Regex.Replace (msg, " +"," ");
结果: 
msg=="1 2 3 4 5 6"

#7


sz_lgp(longguoping) 有点不智能,但这个方法很好
string_xx=string_xx.replace("       "," ")
string_xx=string_xx.replace("      "," ")
string_xx=string_xx.replace("    "," ")
string_xx=string_xx.replace("   "," ")
string_xx=string_xx.replace("  "," ")

#8


string msg="1 2 3  4 5   6"
msg=Regex.Replace (msg, " +"," ");
结果: 
msg=="1 2 3 4 5 6"
没测试,但是msg会不会 = “1+2+3++4+5+++6”啊