这里有一个使用正则表达式的版本,因此您可以指定搜索是否需要区分大小写。为了测试目的,我使用脚本本身的内容作为输入。
Dim path, phrase, content
path = Wscript.ScriptFullName
phrase = "hi there\^$*+?{}.()|[]"
content = CreateObject("Scripting.FileSystemObject").OpenTextFile(path).ReadAll
Function NumberOfPhrasesInString(phrase, text, IgnoreCase)
Dim regexpr, matches
Set regexpr = New RegExp
phrase = RegExEscape(phrase)
With regexpr
.Pattern = phrase
.Global = True
.IgnoreCase = IgnoreCase
Set matches = .Execute(text)
End With
NumberOfPhrasesInString = matches.count
End Function
Function RegExEscape(str)
Dim special
RegExEscape = str
special = "\^$*+?{.()|[]"
For i=1 To Len(special)
RegExEscape = replace(RegExEscape, Mid(special, i, 1), "\" & Mid(special, i, 1))
Next
End Function
Wscript.Echo "Number of times phrase occurs: " & NumberOfPhrasesInString(phrase, content, false)
作为奖励,由于我在这里也切换到了Ruby版本。
path = __FILE__
phrase = 'HI THERE \ ^ $ * + ? { . ( | ['
puts phrase
content = File.read path
def number_of_phrases_in_string(phrase, text, ignoreCase=false )
escaped = Regexp.escape(phrase)
text.scan(Regexp.new(escaped, ignoreCase)).count.to_s
end
puts "Number of times phrase occurs: " + number_of_phrases_in_string(phrase, content, true)
或者在一行中
puts File.read(__FILE__).scan(Regexp.new(Regexp.escape(phrase), true)).count
最后一行的true定义了大小写敏感。
pstrTextToCount
文本两次,它会正确地计算它们吗? - omegastripesInStr
。 - omegastripes