使用VBA正则expression式在逗号后面添加一个空格

我正在尝试使用正则expression式来查找逗号分隔的单元格,但逗号之后没有空格。 然后,我想简单地在逗号和下一个字符之间加一个空格。 例如,一个单元Wayne,BruceWayne,Bruce文本,但我想把它交给Wayne, Bruce

我有一个正则expression式模式,可以find没有空格的字符和逗号的单元格,但是当我replace它时,会切断一些字符。

 Private Sub simpleRegexSearch() ' adapted from http://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops Dim strPattern As String: strPattern = "[a-zA-Z]\,[a-zA-Z]" Dim strReplace As String: strReplace = ", " Dim regEx As New RegExp Dim strInput As String Dim Myrange As Range Set Myrange = ActiveSheet.Range("P1:P5") For Each cell In Myrange If strPattern <> "" Then strInput = cell.Value With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern End With If regEx.TEST(strInput) Then Debug.Print (regEx.Replace(strInput, strReplace)) Else Debug.Print ("No Regex Not matched in " & cell.address) End If End If Next Set regEx = Nothing End Sub 

如果我反对“韦恩,布鲁斯”我得到“韦恩,鲁斯”。 我如何保留这些信件,但将它们分开?

按以下方式更改代码:

 Dim strPattern As String: strPattern = "([a-zA-Z]),(?=[a-zA-Z])" Dim strReplace As String: strReplace = "$1, " 

输出将是Bruce, Wayne

问题是你不能在VBScript中使用后台处理,所以我们需要在逗号之前以字母捕获组的forms提供解决方法。

对于逗号后面的字母,我们可以使用一个前瞻,它在这个正则expression式中可用。

所以,我们只需要捕捉([a-zA-Z]) ,并在返回引用$1的replace调用中恢复它。 预见不会消耗字符,所以我们覆盖。

(编辑) REGEX说明

  • ([a-zA-Z]) – 包含仅匹配1个英文字符的字符类的捕获组
  • , – 匹配文字, (你实际上不必逃避,因为它不是一个特殊的字符)
  • (?=[a-zA-Z]) – 只有在逗号后面的直接字符英文字母的情况下才进行检查(不匹配或消耗)的正面(?=[a-zA-Z])

如果我们用逗号+空格replace所有的逗号 ,然后用逗号+空格replace逗号+空格 +空格 ,我们可以满足您的要求:

 Sub NoRegex() Dim r As Range Set r = Range("P1:P5") r.Replace What:=",", Replacement:=", " r.Replace What:=", ", Replacement:=", " End Sub 

使用与stribizhev的解决scheme相同的RegExp ,但有两个优化的速度

  1. 您当前的代码设置每个testing单元的RegExp详细信息,这些只需要设置一次。
  2. 通过varinat数组循环比单元格范围快得多

 Private Sub simpleRegexSearch() ' adapted from http://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops Dim strPattern As String: Dim strReplace As String: Dim regEx As Object Dim strInput As String Dim X, X1 Dim lngnct Set regEx = CreateObject("vbscript.regexp") strPattern = "([a-zA-Z])\,(?=[a-zA-Z])" strReplace = "$1, " With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern X = ActiveSheet.Range("P1:P5").Value2 For X1 = 1 To UBound(X) If .TEST(X(X1, 1)) Then Debug.Print .Replace(X(X1, 1), strReplace) Else Debug.Print ("No Regex Not matched in " & [p1].Offset(X1 - 1).Address(0, 0)) End If Next End With Set regEx = Nothing End Sub 

你通过Regex做的是find一个模式

 (any Alphabet),(any Alphabet) 

然后replace这样的模式

 ,_ 

这意味着一个空间。

所以,如果你有Wayne,Bruce那么模式匹配在哪里e,B 。 所以结果变成了Wayn, ruce

尝试

 Dim strPattern As String: strPattern = "([a-zA-Z]),([a-zA-Z])" Dim strReplace As String: strReplace = "$1, $2"