简体   繁体   English

如何在vb.net中删除方括号之间的空间?

[英]How to remove space between square brackets in vb.net?

I am using VB.NET to write a winforms application, how can I use regular expression to remove spaces between "[" and "]" in a string? 我正在使用VB.NET编写Winforms应用程序,如何使用正则表达式删除字符串中“ [”和“]”之间的空格?

For example, for a string 例如,对于一个字符串

"[Product Name] Like '%Dragon Ball%' AND [Product Type] Like '%Toy%'"

I want the result to be 我希望结果是

"[ProductName] Like '%Dragon Ball%' AND [ProductType] Like '%Toy%'"

I tried this, but it is not working: 我试过了,但是没有用:

Public Function RemoveSpaceInFieldNames(ByVal expression As String) As String
  Dim regex As RegularExpressions.Regex = New       
  RegularExpressions.Regex(String.Format("\{0}\s*\{1}", "[", "]"))
  Return regex.Replace(expression, String.Empty)
End Function

See regex in use here 查看正则表达式在这里使用

(?<=\[[^]]*)\s
  • (?<=\\[[^]]*) Positive lookbehind ensuring the following matches (?<=\\[[^]]*)正向后方确保满足以下条件
    • \\[ Match [ literally \\[匹配[字面上
    • [^]]* Match any character except ] any number of times [^]]*匹配任何字符除了]任意次数
  • \\s Match any whitespace character \\s匹配任何空格字符

You can append (?=[^[]*]) if you want to ensure there's a ] sometime afterwards as well, but, based on your sample, I don't think this is necessary. 您可以附加(?=[^[]*])如果你想确保有一个]一段时间以后为好,但,根据您的样品,我不认为这是必要的。

Alternatively, you can also use \\s(?=[^[]*]) with the Right to Left modifier as this link shows. 另外,也可以将\\s(?=[^[]*])与“ Right to Left修饰符一起使用,如该链接所示。

Replace with an empty string. 替换为空字符串。

Result: [ProductName] Like '%Dragon Ball%' AND [ProductType] Like '%Toy%' 结果: [ProductName] Like '%Dragon Ball%' AND [ProductType] Like '%Toy%'

Thank you so much ctwheels! 非常感谢您! Your answer works perfectly!!! 您的答案非常完美!!!

Public Function RemoveSpaceInFieldNames(ByVal expression As String) As String
    Dim regex As RegularExpressions.Regex = New RegularExpressions.Regex("(?<=\[[^]]*)\s")
    Return regex.Replace(expression, String.Empty)
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM