Link to home
Start Free TrialLog in
Avatar of Russ Suter
Russ Suter

asked on

Smarter Regex Replace

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.
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Russ Suter
Russ Suter

ASKER

Worked like a charm. I often used parentheses in regex but never understood that they meant capture groups. This expands my usage greatly. Thanks!
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.