Java匹配器模式
我有一个字符串列表:ab10sdj、ba1wqa、cd03asce、dfasc等。我希望从以ab或ba开头的字符串中获得一组数字Java匹配器模式,java,regex,string-matching,matcher,Java,Regex,String Matching,Matcher,我有一个字符串列表:ab10sdj、ba1wqa、cd03asce、dfasc等。我希望从以ab或ba开头的字符串中获得一组数字 因此,如果字符串以ab/ba开头,我需要紧跟其后的一组数字。如果我有办法通过java matcher/regex实现这一点?您可以像这样尝试regex: public static void main(String[] args) { // ab10sdj, ba1wqa, cd03asce, dfasc String s1 = "ab10sdj";
因此,如果字符串以ab/ba开头,我需要紧跟其后的一组数字。如果我有办法通过java matcher/regex实现这一点?您可以像这样尝试regex:
public static void main(String[] args) {
// ab10sdj, ba1wqa, cd03asce, dfasc
String s1 = "ab10sdj";
String s2 = "ba1wqa";
String s3 = "cd03asce";
String s4 = "dfasc";
String pattern = "^(ab|ba)(\\d+).*";
System.out.println(s1.replaceAll(pattern, "$2")); // output 10
System.out.println(s2.replaceAll(pattern, "$2")); // output 1
System.out.println(s3.replaceAll(pattern, "$2")); // output cd03asce i.e, no change
System.out.println(s4.replaceAll(pattern, "$2")); // output dfasc i.e, no change
}
很抱歉将此作为回答,但我目前的声誉水平不允许我发表评论。。。然而:) 与简单地回答一个相对简单的问题(而不损害你的智力)一样,我可以帮助诊断一个解决方案。试着在脑海中一步一步地思考这个问题。即:
祝你的代码一切顺利 对。这是可能的。其实很容易。你试过什么方法来解决这个问题吗?什么问题阻止您完成代码?您回答了自己的问题。正则表达式是前进的方向?