How to replace all strings matching a pattern with correspondinglower case strings ?

A

anonym

Hi,

I am trying to process some text content using Java. I want to
replace all strings matching a pattern with corresponding lower case
strings. For example, replace all <ABCD> with <abcd>

I tried the following, but it doesn't work:

text = text .replaceAll("(<)(.+?)[^(<>)](>)", "$1" + "$2".toLowerCase
() + "$3");

Any help is appreciated.
 
K

Knute Johnson

anonym said:
Hi,

I am trying to process some text content using Java. I want to
replace all strings matching a pattern with corresponding lower case
strings. For example, replace all <ABCD> with <abcd>

I tried the following, but it doesn't work:

text = text .replaceAll("(<)(.+?)[^(<>)](>)", "$1" + "$2".toLowerCase
() + "$3");

Any help is appreciated.

import java.util.regex.*;

public class test {
public static void main(String[] args) {
String str = "lak<XYZ>sdfl234k;j<ABCD>;las3kdfl;jk";
Pattern p = Pattern.compile("(<\\w+>)");
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer();
while (m.find())
m.appendReplacement(sb,m.group(1).toLowerCase());
m.appendTail(sb);
System.out.println(sb.toString());
}
}

"$1".toLowerCase() doesn't work. I assume that's because the
toLowerCase() is applied long before the $1 is replaced by the match.
This example is pretty much right out of the docs for Matcher.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top