Reputation: 7602
I have string with the values: "My name [name], my city [cIty], my country [countrY]..........".
I want to convert all the characters inside square brackets [<value in upper or lower case>]
to [<value in lowercase>]
.
example: [cIty] to [city]
How to do this in a efficient way with less code in java Or Groovy?
EDIT: I want to convert only the characters inside square brackets to lowercase not the other characters outside of square brackets.
Upvotes: 0
Views: 177
Reputation: 171184
A shorter Groovy route is:
def text = "My name [name], my city [cIty], my country [countrY]."
text = text.replaceAll( /\[[^\]]+\]/ ) { it.toLowerCase() }
Upvotes: 2
Reputation: 334
import java.util.regex.*;
public class test {
public static void main(String[] args) {
String str = "My name [name], my city [cIty], my country [countrY]..........";
System.out.println(str);
Pattern pattern = Pattern.compile("\\[([^\\]]*)\\]");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
str = str.substring(0,matcher.start()) + matcher.group().toLowerCase() + str.substring(matcher.end());
}
System.out.println(str);
}
}
Upvotes: 0
Reputation: 4697
Here is some groovy code that should do what you want:
def text = "My name [name], my city [cIty], my country [countrY]."
text.findAll(/\[(.*?)\]/).each{text = text.replace(it, it.toLowerCase())}
assert text == "My name [name], my city [city], my country [country]."
Upvotes: 1
Reputation: 786091
Here is the Java code that will do the job for you:
String str = "My name [Name], My city [cIty], My country [countrY].";
Matcher m = Pattern.compile("\\[[^]]+\\]").matcher(str);
StringBuffer buf = new StringBuffer();
while (m.find()) {
String lc = m.group().toLowerCase();
m.appendReplacement(buf, lc);
}
m.appendTail(buf);
System.out.printf("Lowercase String is: %s%n", buf.toString());
OUTPUT:
Lowercase String is: My name [name], My city [city], My country [country].
Upvotes: 4
Reputation: 836
Am not familiar with Groovy, but in Java, you can do that using string.toLowerCase()
Upvotes: 1