Shailesh Vaishampayan
Shailesh Vaishampayan

Reputation: 1796

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.

Upvotes: 3

Views: 227

Answers (2)

ilomambo
ilomambo

Reputation: 8350

Use

str.replace(/(.*)Hi this is the test for regular Expression/,"$1yourstring")

The .* is greedy, therefore matching the longest possible string, leaving the rest for the explicit string you wanted to match.

Upvotes: 0

Stefan
Stefan

Reputation: 114218

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"

Upvotes: 3

Related Questions