2012-02-21 162 views
1

我沒有很好的在正則表達式的數字之後的所有字符,但那些,但我在努力尋找一種方法來串的字母的情況下,從下改變資本在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... 

我想知道,如果有人可以幫助我產生一個正則表達式來選擇這些字符

預先感謝您

回答

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 

編輯更好的代碼格式。

0

這個怎麼樣?

var str = '2 nd'; 

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

console.log(str);