1

如果最后一个字符以大写字母加数字结尾,我想创建一个生成匹配项并去掉 $ 和最后两个字符的正则表达式。

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]*)

它之所以有效,是因为第一组找到所有那些有 Capitol 后跟数字的人……而第二组找到所有没有后缀的人……

如果您从捕获组中获得匹配项,那就是您想要的。

我认为这样的事情会奏效......

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 回答