我对正则表达式并不擅长,但我正在努力寻找一种方法来改变java中字母从低位到大写字母的情况
Java有一个非常好的方法叫做toUpperCase()但是,由于两个原因,这对我没有帮助。
首先,我希望有一个这样的正则表达式的参考,因为我无法在任何地方找到它,并且 其次,因为它将改变所有角色的情况。
然而,有些情况下我希望保持较低的字符以避免混淆,并使其更好看。
Good Bad
2i = 2I
2o = 2O
1st = 1ST
2nd = 2ND
etc...
是否可以添加条件?例如
"don't replace if the sequence 'st' appears after the number '1' even if there is a space between"
"don't replace if the sequence 'nd' appears after the number '2' even if there is a space between"
etc...
我想知道是否有人可以协助我生成正则表达式以选择那些字符
提前谢谢
答案 0 :(得分:1)
如果你需要的话,请看这个:
final String[] s = { "2 nd blah",
"1st foo",
"foo 2nd bar",
"blahblah1stfounditimmediately",
"blah 3rd foo",
"blah55th foo",
"66 th bar"
};
final Pattern p = Pattern.compile("(1 ?ST|2 ?ND|3 ?RD|\\d+ ?TH)");
Matcher m = null;
String t;
for (final String x : s) {
t = x.toUpperCase();
m = p.matcher(t);
while (m.find()) {
System.out.println(x + " ---> " + t.replaceAll(m.group(1), m.group(1).toLowerCase()));
}
}
以上代码的输出:
2 nd blah ---> 2 nd BLAH
1st foo ---> 1st FOO
foo 2nd bar ---> FOO 2nd BAR
blahblah1stfounditimmediately ---> BLAHBLAH1stFOUNDITIMMEDIATELY
blah 3rd foo ---> BLAH 3rd FOO
blah55th foo ---> BLAH55th FOO
66 th bar ---> 66 th BAR
编辑更好的代码格式。
答案 1 :(得分:0)
怎么样?
var str = '2 nd';
if (!/\d+(\s*)(nd|st)/i.test(str)) {
str = String(str).toUpperCase();
}
console.log(str);