Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java匹配器模式_Java_Regex_String Matching_Matcher - Fatal编程技术网

Java匹配器模式

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";

我有一个字符串列表: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";
    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
}

很抱歉将此作为回答,但我目前的声誉水平不允许我发表评论。。。然而:)

与简单地回答一个相对简单的问题(而不损害你的智力)一样,我可以帮助诊断一个解决方案。试着在脑海中一步一步地思考这个问题。即:

  • 如何测试字符串中的前两个字符
  • 如果对点1的测试通过(即,它们是ab或ba),那么如何处理字符串的其余部分以仅测试“数字”
  • 当到达非数字时,如何停止处理“数字”
  • 一旦您有了ab/ba前缀,仅在测试条件后立即提取“数字”,您将如何处理提取的数字
  • 在考虑将这些数字放置在一个基元类型之前,你可能想考虑一个数字可以预期多少?
    祝你的代码一切顺利

    对。这是可能的。其实很容易。你试过什么方法来解决这个问题吗?什么问题阻止您完成代码?您回答了自己的问题。正则表达式是前进的方向?