Tuesday, April 15, 2008

D'oh! - My Overcomplication of Regex

Some more screwing around with regex more has made me realize I have overcomplicated capture replacement, it is a simple as using a replace and just throwing in the $1, etc into the Regex.Replace functions replace string. I mean what I do works but it is totally unnecessary so I thought I would throw that out there. Apparently they already though of that when they did replace, I wonder why they didnt think of the tristate check treeview since a checkbox can be tristate. Sometimes it is better not to ask why!

The way I did it works well enough but you can see how it could be done below without a temp variable, and it is a little less confusing than using Regex.Result.

Anyway I thought I should share my ignorance, and enlightenment.

ElseIf cbRegEx.Checked = True AndAlso System.Text.RegularExpressions.Regex.IsMatch(txtfind.Text.ToLower, cmbFind.Text) Then
If System.Text.RegularExpressions.Regex.IsMatch(txtfind.Text.Substring(txtfind.SelectionStart, txtfind.SelectionLength), cmbFind.Text) Then

'Smarter, less lines System.Text.RegularExpressions.Regex.Replace(txtfind.Text.Substring(txtfind.SelectionStart, txtfind.SelectionLength), cmbFind.Text, cmbReplace.Text)

'Dumber Many more lines, except the highlighting which is needed
Dim mc As System.Text.RegularExpressions.Match

mc = System.Text.RegularExpressions.Regex.Match(txtfind.Text.Substring(txtfind.SelectionStart, txtfind.SelectionLength), cmbFind.Text)

temprep = cmbReplace.Text

temprep = mc.Result(cmbReplace.Text)


Dim tempstart As Integer = txtfind.SelectionStart

Dim templen As Integer = txtfind.SelectionLength

txtfind.Text = txtfind.Text.Remove(tempstart, templen)

txtfind.Text = txtfind.Text.Insert(tempstart, temprep)

txtfind.SelectionStart = tempstart

txtfind.SelectionLength = temprep.Length

pastend = FindIt()


pastend = FindIt()

End If

No comments: