hvdbunte
hvdbunte

Reputation: 17

Regex Match word between quotes in specific variable

I am new to regular expressions and I am trying to do the following:

LET CustomerName='test';
or
LET CustomerName = 'test';
or
let CustomerName = 'test';

I have this line and I would like to change the test word into something else. So I found this expression:

(?<=LET CustomerName='')[^'']*

And that works for my first example, but I would like to make it more robust so it can also recognize the second line.

I found this code to replace something between quotes but I would like to only change the value between quotes in the specific line.

(?<=(["']))(?:(?=(\\?))\2.)*?(?=\1)

Thanks for your help.

Upvotes: 0

Views: 346

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

You might use

(?<=CustomerName\s*=\s*')[^']+(?=')

The pattern matches:

  • (?<=CustomerName\s*=\s*') Positive lookbehind, assert directly to the left CustomerName followed by = between optional whitspace chars
  • [^']+ match 1+ times any char except ' using a negated character class
  • (?=') Positive lookahead, assert ' directly to the right

.NET regex demo (click on the Context tab to see the replacements)

Example

$strings = @("LET CustomerName='test';", "LET CustomerName = 'test';", "let CustomerName = 'test';")
$strings -replace "(?<=CustomerName\s*=\s*')[^']+(?=')","[replacement]"

Ouput

LET CustomerName='[replacement]';
LET CustomerName = '[replacement]';
let CustomerName = '[replacement]';

If you want to match either a single or a double quote at each side, and allow matching for example a double quote between the single quotes, you can use a capture group for one of the chars (["']).

Then continue matching all that is not equal to what is captured using a backreference \1 until to can assert what is capture to the right.

(?<=CustomerName\s*=\s*(["']))(?:(?!\1).)+(?=\1)

.NET Regex demo

Or allowing escaped single and double quotes using atomic groups:

(?<=CustomerName\s*=\s*(["']))(?>(?!\1|\\).)*(?>\\\1(?>(?!\1|\\).)*)*(?=\1)

.NET regex demo

Upvotes: 3

Related Questions