繁体   English   中英

如何在VBA宏中使用regexp解析Excel的单元格字符串

[英]How to parse Excel's cell string with regexp in VBA macro

我正在Excel 2010中编写宏,以删除列的多个单元格中的换行符。 实际上,我有5个案例需要在单元格中进行搜索。 我列举如下:

  1. 如果有一个点或逗号后跟一个空格,然后是一个换行符(\\ n),则将其替换为点或逗号(应用regexp之前的内容)和一个空格
  2. 如果有一个字符,后接空格和换行符,则将其替换为字符和空格
  3. 如果后面有换行符,请用字符+空格替换
  4. 如果有一个字符,其后是两个空格,然后是换行符,则将其替换为字符+空格
  5. 如果该行的末尾有一个点,则将其保留为那样,因为它是一个结束点。

如您所见,2和3确实很相似,所以我认为正则表达式可能类似于[a-zA-Z0-9]\\n但我不知道...首先,如果搜索a是正确的换行符只需加上\\ n一秒钟,如何搜索空格。 在检测到regexp之后,我认为可以用单个.Replace(Text,"regexp","regexp ")来解决,其中末尾空格来自“ char” +“”形式
所以基本上我的问题是,这种模式的正则表达式可能是什么? 在第5种情况下,我如何搜索行终止符,这样它就不会尝试在段落的最后一个点之后搜索换行符。
我可以将Chr(10)用于换行符,并将Chr(32)用于空格吗?
顺便说一句,我一直在遵循这些参考:
如何使用RegExp
VBA分割字串

此模式将找到任何字母数字字符. ,或,后跟可选的空白,然后是换行符,并用匹配的结尾字符替换,后跟一个空格。

Dim re
Set re = CreateObject("VBScript.RegExp")
re.Pattern = "([\w.,])\s*\n"
strText = re.Replace(strText, "$1 ")

测试的输出。 忽略括号。 他们只是在那里展示空间。

[the end.]     = [the end.]
[the end.\n]   = [the end. ]
[the end. \n]  = [the end. ]
[the end.  \n] = [the end. ]
[the end,]     = [the end,]
[the end,\n]   = [the end, ]
[the end, \n]  = [the end, ]
[the end,  \n] = [the end, ]
[the end]      = [the end]
[the end\n]    = [the end ]
[the end \n]   = [the end ]
[the end  \n]  = [the end ]

暂无
暂无

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

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