Smarter Regex Replace

Russ Suter
Russ Suter used Ask the Experts™
on
Given the following string:
SELECT * FROM myTable WHERE Description LIKE 'some text'

Open in new window

I am using a regular expression as follows:
[^[][*'][^]]

Open in new window

This easily detects an asterisk or squote character that isn't enclosed in brackets. What I'd like to do is create a single regular expression that adds square brackets around a "naked" asterisk or squote character. I could do it with two discreet regex calls but I'm hoping there's a smarter way to build the regular expression such that if it finds any character in the middle part that it is automatically enclosed in square brackets.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
Add a capture group (i.e. parentheses):

[^[]([*'])[^]]

Open in new window


Then use that group in your replace:

string result = Regex.Replace(source, "[^[]([*'])[^]]", "[$1]");

Open in new window

Russ SuterSenior Software Developer

Author

Commented:
Worked like a charm. I often used parentheses in regex but never understood that they meant capture groups. This expands my usage greatly. Thanks!
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Keep in mind that capture groups are numbered from left to right. So given the following:

(abc)(123)

Open in new window


...capture group 1 will contain "abc" and capture group 2 will contain "123". Capture groups can also be nested:

((hello) world), (it's me)

Open in new window


Numbering here is slightly trickier, but more or less the same. It's still left to right, but as you encounter a new opening paren, the numbering increases. In this case, "hello world" is capture group 1, just "hello" is in capture group 2, and "it's me" is in capture group 3.

When you want to access a capture group, then you use the syntax "\n" or "$n", where "n" is the number of the group. ("\0" and "$0" are special capture groups which represent the entire matched string, regardless of any other capture groups.) Which you use depends on where you are working. If you are trying to use the capture group within the pattern itself, then you use the slash version. If you are working within the replacement, then you use the dollar version.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial