user811433
user811433

Reputation: 4149

How to convert a string from one pattern to another using regex?

I have a string I want to convert using regex:

AA_BB_CC_DD => EE_BB_FF_DD

Tried using regex like (AA)(.*)(FF). But that did not work. can someone help?

Also it would be nice if you can point me to a good regex guide. There are too many sites for regex. not sure which to refer.

Upvotes: 0

Views: 3479

Answers (2)

mki
mki

Reputation: 635

If you want complete explanations you can have a look here : http://www.regular-expressions.info/tutorialcnt.html

When you understand how it works the Pattern API is enough.

For your example, I suppose that AA -> EE, BB -> BB, CC -> FF, DD -> DD So you can try the following :

String before = "AA_BB_CC_DD";
String after = before.replaceAll("AA_(.*)_CC_(.*)", "EE_$1_FF_$2");

And you get the result. I explain the regex :
"AA_(.*)CC(.*)"
The program try to match AA_, . means any character and * means repeat it. Thus any string between AA_ and CC is matched. The () indicate a group which is "memorized".

"EE_$1_FF_$2"
AA_ is replaced with EE_. $1 means print the first group ().
Same for FF and $2.

Upvotes: 1

MikeM
MikeM

Reputation: 13631

How about

String before = "AA_BB_CC_DD";
String after = before.replaceFirst("AA(_BB_)CC(_DD)", "EE$1FF$2");

System.out.println(after);
// EE_BB_FF_DD

You haven't described how the form of the input string my vary, so it is difficult to produce a suitable regex.

If you wanted to allow almost anything between the AA and CC you could use (.*?) instead of (_BB_) etc.

The above shows the principle of using in the replacement string the content that is captured by the () , i.e. $1 refers to the content in the first (), and $2 the second ().

Links:
Regular-expressions.info.
The Java Tutorials. Lesson: Regular Expressions.

Upvotes: 2

Related Questions