我有字符串的值:“我的名字[名字],我的城市[cIty],我的国家[国家] ..........”。如何替换字符串
我想将方括号内的所有字符[<value in upper or lower case>]
转换为[<value in lowercase>]
。
例如:[城市]到[城市]
如何在Java或Groovy更少的代码做一个有效的方式?
编辑:我只想将方括号内的字符转换为小写,而不是方括号外的其他字符。
我有字符串的值:“我的名字[名字],我的城市[cIty],我的国家[国家] ..........”。如何替换字符串
我想将方括号内的所有字符[<value in upper or lower case>]
转换为[<value in lowercase>]
。
例如:[城市]到[城市]
如何在Java或Groovy更少的代码做一个有效的方式?
编辑:我只想将方括号内的字符转换为小写,而不是方括号外的其他字符。
下面是一些应该做你想做的事的代码:
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]."
这里是Java代码,会为你做的工作:
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].
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);
}
}
较短Groovy的路线是:
def text = "My name [name], my city [cIty], my country [countrY]."
text = text.replaceAll(/\[[^\]]+\]/) { it.toLowerCase() }
酷! :-)还有一条较短的路径,不需要你在循环中重复设置'text'变量:http://stackoverflow.com/a/12932736/6509 :-) –