Java 正则表达式以查找除数字之后的字符以外的所有字符

Java 正则表达式以查找除数字之后的字符以外的所有字符,java,regex,Java,Regex,我不擅长regexps,但我正在努力找到一种方法,在java中将字符串的字母大小写从小写改为大写 Java有一个非常好的方法,名为toUpperCase(),但是,这并不能真正帮助我,原因有二 首先,我希望有这样一个regexp的参考,因为我在任何地方都找不到它,而且 第二,因为它将改变所有字符的大小写 不过,在某些情况下,我希望保留较低的字符以避免混淆,并使其更美观 Good Bad 2i = 2I 2o = 2O 1st = 1ST 2nd = 2ND etc... 是

我不擅长regexps,但我正在努力找到一种方法,在java中将字符串的字母大小写从小写改为大写

Java有一个非常好的方法,名为toUpperCase(),但是,这并不能真正帮助我,原因有二

首先,我希望有这样一个regexp的参考,因为我在任何地方都找不到它,而且 第二,因为它将改变所有字符的大小写

不过,在某些情况下,我希望保留较低的字符以避免混淆,并使其更美观

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...
我想知道是否有人可以帮助我生成一个regexp来选择这些字符

提前谢谢你

这个怎么样

var str = '2 nd';

if (!/\d+(\s*)(nd|st)/i.test(str)) {
    str = String(str).toUpperCase();
}​​​​​​​​​​

console.log(str);

这个怎么样

var str = '2 nd';

if (!/\d+(\s*)(nd|st)/i.test(str)) {
    str = String(str).toUpperCase();
}​​​​​​​​​​

console.log(str);

如果这是您需要的,请查看以下内容:

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

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

如果需要,请查看以下内容:

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
编辑以获得更好的代码格式