vba regEx 替换未按预期删除空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1976153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 11:09:29  来源:igfitidea点击:

regEx replace not removing spaces as expected

regexvbaexcel-vbaexcel

提问by Seth

Here is the typical string I am working with:

这是我正在使用的典型字符串:

·???????? Identify & document site-related constraints and assumptions.

I would like to scrub that string to get rid of everything before "Identify"...

我想在“识别”之前擦洗该字符串以清除所有内容...

I wrote a function to take the string and scrub it, here it is:

我写了一个函数来获取字符串并擦洗它,这里是:

Function dataScrub(dataIn As String)
Dim dataIn_orig As String
dataIn_orig = dataIn

'BEGIN : create and set regular expression
Dim regEx
Set regEx = CreateObject("vbscript.regexp")
With regEx
        .IgnoreCase = True
        .MultiLine = False
        .Pattern = "^[\s]*[·]+[\s]*"
        .Global = True
End With

dataScrub = regEx.Replace(dataIn_orig, "")
End Function

For an unknown reason, the replace is replacing the · (not a period, more like a bullet) but not getting rid of the spaces that follow it, so my end result is:

出于未知原因,替换正在替换 ·(不是句号,更像是子弹)但没有去掉它后面的空格,所以我的最终结果是:

      Identify & document site-related constraints and assumptions.

When I test my regEx using an online tester (http://www.regular-expressions.info/javascriptexample.html), it works as intended.

当我使用在线测试器 ( http://www.regular-expressions.info/javascriptexample.html)测试我的 regEx 时,它按预期工作。

What am I doing wrong?

我究竟做错了什么?

采纳答案by Welbog

[\s]matches either a \or an s. Try using just plain old \swithout the square braces.

[\s]匹配 a\s。尝试使用\s没有方括号的普通旧款。



Well, since that still doesn't work, the last \s*might be a reluctant match instead of a greedy one. You should be able to fix that by adding a \bto the end of your expression. \bindicates a word boundary (either before or after a word). Give this one a try:

好吧,既然那仍然不起作用,那么最后一个\s*可能是不情愿的匹配而不是贪婪的匹配。您应该能够通过\b在表达式的末尾添加 a 来解决这个问题。\b表示单词边界(在单词之前或之后)。试试这个:

^\s*[·]+\s*\b

回答by Irwin M. Fletcher

Looks like the answer has been accepted already, but running this line of code in your function will take care of you issue as well.

看起来答案已经被接受,但是在您的函数中运行这行代码也会解决您的问题。

Cells.Replace What:=Chr(160), Replacement:="", LookAt:=xlPart