2012-02-21 10 views
1

数字の後のすべての文字BUTものを見つけることが、私は正規表現は、私は正規表現では良い午前ない

Javaが持っているJavaで首都に下から文字列の大文字と小文字を変更する方法を見つけるのに苦労していますtoUpperCase()と呼ばれる非常に素晴らしいメソッドですが、これは2つの理由で私を助けません。

まず、私はどこでも見つけることができなかったので、このような正規表現の参照をしたいと思います。 2番目の文字はすべての文字の大文字と小文字が変更されるためです。

しかし、私は混乱を避けるために、より低い文字を保ちたいと思う場合があります。

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 

EDITを。

0

方法をありがとう!

var str = '2 nd'; 

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

console.log(str);