3

次の文字列があります

sssHi これは正規表現のテストです,sr,Hi これは正規表現のテストです

だけ交換したい

こんにちは、これは正規表現のテストです

他の文字列でセグメント化します。

文字列 "sss Hi this is the test for regular Expression " の最初のセグメントは置き換えないでください

同じものに対して次の正規表現を書きました:

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

ただし、両方のセグメントに一致します。最初のセグメントの前に「sss」が付いているため、2 番目のセグメントのみを一致させたいと考えています。

[^.]      

改行以外は一致しないはずですよね? そうグループ

  "([^.]anystring)"

改行以外の任意のチャンラクターが前にない「任意の文字列」にのみ一致する必要があります。私は正しいですか?

何かご意見は。

4

2 に答える 2

3

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"
于 2012-07-16T13:40:02.627 に答える
0

使用する

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

. *は貪欲であるため、可能な限り長い文字列に一致し、残りは一致させたい明示的な文字列に残します。

于 2012-07-16T15:35:12.543 に答える