gpt4 book ai didi

java - 正则表达式查找除数字后面的所有字符

转载 作者:太空宇宙 更新时间:2023-11-04 08:21:55 26 4
gpt4 key购买 nike

我不擅长正则表达式,但我正在努力寻找一种方法来将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...

我想知道是否有人可以帮助我生成正则表达式来选择这些字符

提前谢谢

最佳答案

如果这是您需要的,请查看:

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

编辑以获得更好的代码格式。

关于java - 正则表达式查找除数字后面的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9378191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com