Addev
Addev

Reputation: 32233

Regexp to replace a String with a number in the middle

I'd like to replace a string with format

XXXXXXXXXXstart_N_endYYYYYYYYYY

(where N is a integer [can have multiple digits], and start, end are known fixed strings) removing the start_N_end.

So the result should be

XXXXXXXXXXYYYYYYYYYY

A real example: I need to replace Input_0_key with MyKey

<input id="Input_0_key" name="Input_0_key" size="30" type="text">

Note: I need to make the replacement using a regexp, can't use a DOM parser or similar.

Thanks in advance

Upvotes: 0

Views: 998

Answers (4)

Jean-Bernard Pellerin
Jean-Bernard Pellerin

Reputation: 12670

If you're using java which I suspect you are from your history:

str.replaceAll("(\"[^\"]*?)Input_\\d*_key([^\"]*\")","$1$2");

will take "hiInput_12312312_keyhello" and return "hihello"

Upvotes: 1

user2008074
user2008074

Reputation:

As simple as s/Input_\d+_key/MyKey/g.

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

try this in php:

$string = '<input id="Input_0_key" name="Input_0_key" size="30" type="text">';
$pattern = '~<input id="\K[^"]++(?=" name="Input_0_key" size="30" type="text">)~';
echo preg_replace($pattern, 'Youhou', $subject);

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191729

s/Input.*?key/MyKey

The .*? will match as little as possible between Input and key.

Upvotes: 1

Related Questions