hellzone
hellzone

Reputation: 5236

How to extract and replace a String with specific format?

I have input String like;

(rm01ADS21212, 'adfffddd', rmAdssssss, '1231232131', rm2321312322)

What I want to do is find all words starting with "rm" and replace them with remove function.

(remove(01ADS21212), 'adfffddd', remove(Adssssss), '1231232131', remove(2321312322))

I am trying to use replaceAll function but I don't know how to extract parts after "rm" literal.

statement.replaceAll("\\(rm*.,", "remove($1)");

Is there any way to get these parts?

Upvotes: 3

Views: 166

Answers (2)

mssranjani
mssranjani

Reputation: 1

Use "Replace" with empty string .

Eg;

string str = "(rm01ADS21212, 'adfffddd', rmAdssssss, '1231232131', rm2321312322)";
 Console.WriteLine(str.Replace("rm", ""));

Output : (01ADS21212, 'adfffddd', Adssssss, '1231232131', 2321312322)

Upvotes: -3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You have not captured any substring with a capturing group, thus $1 is null.

You may use

.replaceAll("\\brm(\\w*)", "remove($1)")

See the regex demo

Details

  • \b - a word boundary (to start matching only at the start of a word)
  • rm - a literal part
  • (\w*) - Group 1: 0+ word chars (letters, digits or underscores)

The $1 in the replacement pattern stands for Group 1 value.

If you mean to match any chars other than a comma and whitespace after rm, use "\\brm([^\\s,]*)", see this regex demo.

Upvotes: 5

Related Questions