RegEx, the mind-flayer.
I’m new to RegEx, and I’ve got a search pattern almost nailed down (maybe?).
I have a paragraph of text which contains various sets of brackets, each containing a single uppercase letter. ie: (A), (B), (C), and so on.
I’ve managed to isolate those and replace them with “”. The problem is that the search also replaces the end of a sentence in brackets. ie: (Some guy said that) becomes (Some guy said tha
I only want to replace brackets that contain a single character, along with that character.
My current code is in the pressed event of a button:
Var rg As New RegEx
Var myMatch As RegExMatch
Var resultTxt As String
rg.SearchPattern = "([^()]{2})"
// variable s is the paragraph of text I'm using
myMatch = rg.Search(s)
Do
If myMatch <> Nil Then
resultTxt = resultTxt + myMatch.SubExpressionString(0)
myMatch = rg.Search
End If
Loop Until myMatch Is Nil
If anyone wants to see the text (Var s as string) I’m running this on, I can post that.
Any help in solving this would be immensely appreciated!
Try
Var rg As New RegEx
Var ro As New RegExOptions
rg.SearchPattern = "\([A-Z]\)"
rg.ReplacementPattern = ""
ro.ReplaceAllMatches = True
rg.Options = ro
rg.Replace(s)
‘(’ and ‘)’ have special meaning in the regular expression. They form groups of various kinds, usually capturing groups you can access later using the RegExMatch.SubExpressionString() function, where SubEspressionString(0) is the entire match, SubExpressionString(1) is what matched with the regular expression within the first pair of parentheses and so on. We need to actually match the parenthesis-characters, so we need to quote them within the regular expression using a ‘\’. `[A-Z]’ just matches any single uppercase alphabetic ASCII character.
Using the rg.Replace function helps you to not have to mess with the RegExMatch and it’s byte based positions and length at all.
In your pattern ‘(’ and ‘)’ just form a capturing group. They are not searched for. [^()]{2} matches any two consecutive characters of which neither one is an opening or closing parenthesis.
In your loop, processing the result, you concatenate all the matches. With my search pattern you would get something like (A)(B)(C). Instead, if you wanted to process the matches in a loop, you would need to copy the string before the match and append the string after the match, something the Replace function will do much easier, and likely much faster.
By the way, I guess your result above likely does not contain the opening parenthesis either. Processing your code in my head on the strung will result in Some guy said tha.
Excellent, works like a charm! Thank you so much for the solution and the explanation! It’ll take me a bit of time to wrap my head around what you’ve said, but my old brain will get there.
Oh, btw, for some weird reason the sentence “(Some guy said tha” did actually did have the opening parenthesis. At any rate, your (oh, so simple) solution does the desired job. 