Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is regular expression in javascript

I have following string

sssHi this is the test for regular Expression,sr,Hi this is the test for regular Expression

I would like to replace only

Hi this is the test for regular Expression

segment with some other string.

the first segment in string "sss Hi this is the test for regular Expression" should not be replaced

I wrote following regex for the same :

/([^.]Hi\sthis\sis\sthe\stest\sfor\sregular\sExpression)|(Hi\sthis\sis\sthe\stest\sfor\sregular\sExpression)$/

but it matches both segments. I want to match only the second one as first segement is prefixed by "sss".

[^.]      

should match nothing except newline right? So group

  "([^.]anystring)"

should only match "anystring" that is not preceded by any chanrachter except newline. Am I correct?

any thoughts.

like image 838
Shailesh Vaishampayan Avatar asked Jan 26 '26 01:01

Shailesh Vaishampayan


1 Answers

Matching a string that is not preceded by another string is a negative lookbehind and not supported by JavaScript's regex engine. You can however do it using a callback.

Given

str = "sssHi this is the test for regular Expression,sr,Hi this is the test for regular Expression"

Use a callback to inspect the character preceding str:

str.replace(/(.)Hi this is the test for regular Expression$/g, function($0,$1){ return $1 == "s" ? $0 : $1 + "replacement"; })
// => "sssHi this is the test for regular Expression,sr,replacement"

The regex matches both strings so the callback function is invoked twice:

  1. With
    • $0 = "sHi this is the test for regular Expression"
    • $1 = "s"
  2. With
    • $0 = ",Hi this is the test for regular Expression"
    • $1 = ","

If $1 == "s" the match is replaced by $0, so it remains unchanged, otherwise it is replaced by $1 + "replacement".

Another approach is to match the second string, i.e. the one you want to replace including the separator.

To match str preceded by a comma:

str.replace(/,Hi this is the test for regular Expression/g, ",replacement")
// => "sssHi this is the test for regular Expression,sr,replacement"

To match str preceded by any non-word character:

str.replace(/(\W)Hi this is the test for regular Expression/g, "$1replacement")
// => "sssHi this is the test for regular Expression,sr,replacement"

To match str at the end of line:

str.replace(/Hi this is the test for regular Expression$/g, "replacement")
// => "sssHi this is the test for regular Expression,sr,replacement"
like image 156
Stefan Avatar answered Jan 27 '26 14:01

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!