Regex 正则表达式匹配计数
我试图计算字符串中被替换的匹配项的数量,但问题是,只有当要替换的单词被隔开或在每行中时,它才会正确计算。例如: 墙墙墙墙墙墙墙墙 在上面的字符串中,我想将所有出现的“the”替换为单词cars。字符串中出现了5次“the”。要替换,我使用以下命令:Regex 正则表达式匹配计数,regex,vb.net,count,match,Regex,Vb.net,Count,Match,我试图计算字符串中被替换的匹配项的数量,但问题是,只有当要替换的单词被隔开或在每行中时,它才会正确计算。例如: 墙墙墙墙墙墙墙墙 在上面的字符串中,我想将所有出现的“the”替换为单词cars。字符串中出现了5次“the”。要替换,我使用以下命令: Private Function GetRegExpression() As Regex Dim result As Regex Dim regExString As [String] ' Get what the user ent
Private Function GetRegExpression() As Regex
Dim result As Regex
Dim regExString As [String]
' Get what the user entered
regExString = txtbx_Find.Text
Dim baseRegex As Regex = New Regex("[\\.$^{\[(|)*+?]")
regExString = baseRegex.Replace(regExString, "\$0")
If chkMatchCase.Checked Then
result = New Regex(regExString)
Else
result = New Regex(regExString, RegexOptions.IgnoreCase)
End If
Return result
End Function
Private Sub btn_ReplaceAll_Click(sender As Object, e As EventArgs) Handles btn_ReplaceAll.Click
Dim regCount As New Regex(txtbx_Find.Text)
Dim matchCount As Integer = 0
Dim replaceRegex As Regex = GetRegExpression()
Dim replacedString As [String]
' get the current SelectionStart
Dim selectedPos As Integer = TheTextBox.SelectionStart
' get the replaced string
Dim aCount = regCount.Matches(TheTextBox.Text).Count
replacedString = replaceRegex.Replace(TheTextBox.Text, txtbx_Replace.Text)
' Is the text changed?
If TheTextBox.Text <> replacedString Then
' then replace it
TheTextBox.Text = replacedString
If aCount < 2 Then
lbl_RepMade.Text = String.Format("{0} replacement successfully made.", aCount)
Timer1.Start()
ElseIf aCount > 2 Then
lbl_RepMade.Text = String.Format("{0} replacements successfully made.", aCount)
Timer1.Start()
End If
Else
' inform user if no replacements are made
MessageBox.Show(String.Format("Cannot find ""{0}"" ", txtbx_Find.Text), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
之后:
Dim regCount As New Regex(txtbx_Find.Text, RegexOptions.IgnoreCase)
Dim regCount As New Regex(txtbx_Find.Text, RegexOptions.IgnoreCase)
添加IgnoreCase解决了我的问题。它总是搜索准确的方式,包括用户搜索并想要替换的案例 以下是OP解决问题的方法: 之前:
Dim regCount As New Regex(txtbx_Find.Text)
Dim regCount As New Regex(txtbx_Find.Text)
之后:
Dim regCount As New Regex(txtbx_Find.Text, RegexOptions.IgnoreCase)
Dim regCount As New Regex(txtbx_Find.Text, RegexOptions.IgnoreCase)
添加IgnoreCase解决了我的问题。它总是搜索准确的方式,包括用户搜索并想要替换的案例
是否确实选中了“忽略大小写”复选框?如果选中该复选框,并且用户找到了“the”,则不会进行替换,因为没有匹配的大小写开始。如果是,则只搜索并替换匹配的大小写单词。所以我的问题是,当它没有被选中时,它将同时搜索大写和小写,如果有小写,那么将只计算小写。我的大写字母发现有问题。。