1

最後の文字が大文字と数字で終わる場合、一致を生成して $ と最後の 2 文字を削除する正規表現を作成したいと考えています。

I'll strip off the $ and then an ending capital letter + number:

$mytestA1 --> expected output: mytest
$againD4 --> expected output: again
$something --> expected output: something
$name3 --> expected output: name3 // because there was no capital letter before the number digit
$name2P4 --> expected output: name2

わざわざ正規表現を実行する前に、$ の存在をチェックする「if」チェックをコードに入れます。

ありがとう。

4

2 に答える 2

1

これは最も効率的ではないかもしれませんが、うまくいくでしょう...

\$([^\s]*)(?:[A-Z]\d)|\$([^\s]*)

最初のセットは国会議事堂の後に数字が続くものをすべて見つけ、2番目のセットは接尾辞のないものをすべて見つけるので、うまくいきます...

あなたが望むものであるキャプチャグループから一致を取得する場合。

このようなものはうまくいくと思います...

import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class HereYouGo {
    public static void main (String args[]) {

        String input = "$mytestA1 --> expected output: mytest\r\n$againD4 --> expected output: again\r\n$something --> expected output: something\r\n$name3 --> expected output: name3 // because there was no capital letter before the number digit\r\n$name2P4 --> expected output: name2\r\n";      

        Pattern myPattern = Pattern.compile("\\$([^ ]*)(?:[A-Z]\\d)|\\$([^ ]*)", Pattern.DOTALL | Pattern.MULTILINE);

        Matcher myMatcher = myPattern.matcher(input);

        while(myMatcher.find())
        {
            String group1 = myMatcher.group(1);
            String group2 = myMatcher.group(2);

            //note: this should probably be changed in the case neither match is found
            System.out.println( group1!=null? group1 : group2 );
        }
    }
}

これにより、次のように出力されます

mytest
again
something
name3
name2
于 2012-05-21T20:41:38.230 に答える
1

Java では String#replaceAll を使用します。

String replaced = str.replaceAll("^\\$|[A-Z]\\d$", "");
于 2012-05-21T20:49:01.767 に答える