下面是正则表达式函数样例,请使用该函数,从给定的原文本中,找出所需要的文本(查找目标/模式)。
RegExp Function
1.Function RegExpTest(patrn, strng)
2. Dim regEx, Match, Matches, str
3. Set regEx = New RegExp
4. regEx.Pattern = patrn
5. regEx.IgnoreCase = True
6. regEx.Global = True
7. Set Matches = regEx.Execute(strng)
8. For Each Match in Matches
9. str = str & "Match found at position “
10. str = str & Match.FirstIndex & ". Match Value is '"
11. str = str & Match.Value & "'." & vbNewLine
12. Next
13. RegExpTest = str
14.End Function
请根据需要,设计灵活的模式,以便能够利用正则表达式,实现相应的目标。
目标1:请在红楼梦小说里,查找有关于贾宝玉的名字一共出现多少次?(红楼梦的小说已经给出)。
目标2:(选做)
据说,红楼梦小说前80回是曹雪芹原著,后40回是高鹗所写,你能使用正则表达式,通过设计合适的模式(可以是多个模式),用实验结果,来验证这一说法吗?
注意:
小说中,关于贾宝玉的名字有贾宝玉、宝玉,除此以外,还有以下称呼:
1.混世魔王(王夫人云);
2.绛洞花王(从李纨口中得知,或为其自封);
3.富贵闲人(薛宝钗谑云);
4.无事忙(薛宝钗讽曰);
5.怡红公子(林黛玉与)
6.御赐道号:文妙真人;
7.书中作者对其的称呼:情哥哥、多情公子等;
8.太虚幻境的称号:神瑛侍者。
关于第1题,我写了以下代码:
Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches, str
Set regEx = New RegExp
regEx.Pattern = patrn
regEx.IgnoreCase = True
regEx.Global = True
Set Matches = regEx.Execute(strng)
For Each Match in Matches
str = str & "Match found at position "
str = str & Match.FirstIndex & ". Match Value is '"
str = str & Match.Value & "'." & vbNewLine
Next
RegExpTest = str
End Function
Dim filePath, pattern, text ,result
filePath ="D:\qtp\《红楼梦》作者:曹雪芹.txt"' 替换为红楼梦小说的实际路径
pattern = "贾宝玉" ' 要查找的名字
text = ReadTextFile(filePath)
result = RegExpTest(pattern, text)
Dim matches
matches = Split(result, vbNewLine)
WScript.Echo "Number of occurrences of '贾宝玉': " & UBound(matches) - 1
但是qtp里面运行发生了报错:
这要怎么解决呢?