【问题标题】:OCP 7 II regular expression [duplicate]OCP 7 II 正则表达式 [重复]
【发布时间】:2015-01-03 14:40:31
【问题描述】:
import java.util.regex.*;

public class Regex2 {

    public static void main(String[] args) {
        Pattern p = Pattern.compile("\\d*");
        Matcher m = p.matcher("ab34ef");
        boolean b = false;
        while ( m.find()) {
            System.out.print(m.start() + m.group());
        }
    }
}

为什么这段代码会产生输出:01234456

【问题讨论】:

  • 如果您使用println,您会更清楚地了解发生了什么。

标签: java regex


【解决方案1】:

@vks 是对的: 如果您使用\\d*,它适用于每个字符:

Index: char = matching:
    0: 'a'  = "" because no integer
    1: 'b'  = "" because no integer
    2: '3'  = "34" because there is two integer between index [2-3]
       '4'    is not checked because the index has been incremented in previous check.
    4: 'e'  = ""
    5: 'f'  = "" because no integer
    6: ''   = "" IDK

它产生 0, "", 1, "", 2, "34", 4, "", 5, "", 6, "" = 01234456 (这就是你得到它的原因)。

如果您使用\\d+,则只有具有一个或多个整数的组会匹配。

【讨论】:

    【解决方案2】:
    \d* means integer 0 or more times.So an empty string between a and b ,before a ...those are also
    
    matched.Use `\d+` to get correct result.
    

    查看演示。

    https://www.regex101.com/r/fG5pZ8/25

    【讨论】:

      【解决方案3】:

      因为\\d* 表示零个或多个数字。

      作为,

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多