0

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.

0

1 Answer 1

3

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) 

(?!\1|\\).)*(?>\\\1(?>(?!\1|\\).)*)*(?=\1)&i=LET+CustomerName='test';LET+CustomerName+=+'test';let+CustomerName+=+'test';LET+CustomerName="te\"st";LET+CustomerName+=+"test";let+CustomerName+=+"test";LET+CustomerName="test';LET+CustomerName+=+'test";let+CustomerName+=+"t'est";let+CustomerName+=+'t"e"st';LET+CustomerName='te\'st';&r=[Replacement]" rel="nofollow noreferrer">.NET regex demo

Sign up to request clarification or add additional context in comments.

4 Comments

lookbehind is not supported in all regexp flavours and some only support fix length expressions. In Powershell this is fine. To include the leading LET or let you could add (?:let|LET) od [Ll][Ee][Tt]
@bw_üezi That is why I used the quantifiers in the lookbehind because it is supported.
@bw_üezi: See the .net-demo at the end of the answer - +1.
@Thefourthbird Is it also possible to check between '' if it is an empty string? LET CustomerName='';

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.