简单的正则表达式匹配

时间:2012-05-21 20:24:12

标签: java regex

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

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'检查,检查是否存在$在我甚至懒得运行正则表达式之前。

感谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

在Java中只使用String#replaceAll:

String replaced = str.replaceAll("^\\$|[A-Z]\\d$", "");