【问题标题】:Validate Repeated Exact Match Pattern with Optional Word使用可选单词验证重复的精确匹配模式
【发布时间】:2014-03-21 06:44:39
【问题描述】:

我正在尝试读取模式输入字符串。让我们假设这个输入字符串在每个字符串中都被新的空格分隔。

第一个数字字符串(一,二,三,...)是强制性的,可选的数字字符串可以是可选的,直到它遇到操作数然后出现在相同的数字字符串模式之后。 例如,

ONE TWO ADD TWO FIVE // which is valid
ONE ADD TWO // which is valid
TWO SUB FIVE // also is valid
SUB TWO // is not valid

如何使用正则表达式查找模式?我刚开始使用 Java 的 Pattern 和 Matcher 类。

    public boolean validate(String inputStr) {
    // pattern regex
    /* (zero|one|two|three|four|five|six|seven|eight|nine)\\s(zero|one|two|three|four|five|six|seven|eight|nine)?\\s(add|sub) */
    Pattern p = Pattern.compile("(zero|one|two|three|four|five|six|seven|eight|nine)\\s[(zero|one|two|three|four|five|six|seven|eight|nine)]?\\s(add|sub|divide|multiply)\\s(zero|one|two|three|four|five|six|seven|eight|nine)", Pattern.CASE_INSENSITIVE);
    // input string
    Matcher m = p.matcher(inputStr);

    return m.matches();
}

它返回假。

    boolean isValidate = validate("One add two ");
    System.out.println(isValidate);

谁能帮我解决这个问题?谢谢。

【问题讨论】:

    标签: java regex


    【解决方案1】:

    这是因为当可选的数字字符串不存在时,它也会占用空间,所以所有这些都将在第一个不存在的字符串之后匹配两个空格,并且你得到错误。所以移动空格也在方括号内。

    试试这个,

    Pattern p = Pattern.compile("((zero|one|two|three|four|five|six|seven|eight|nine)\\s){1,2}(add|sub|divide|multiply)(\\s(zero|one|two|three|four|five|six|seven|eight|nine)){1,2}", Pattern.CASE_INSENSITIVE);
    

    【讨论】:

    • 这会为第一个 "ONE TWO ADD TWO FIVE" 返回 false
    • 是的,它也为"ONE FIVE ADD TWO" 返回false
    • 修改了我上面的那个。效果很好,您可以将其扩展到任意数量的情况。
    • @RKC 嘿,从我的问题来看,你是对的。我需要在操作数之前和之后是无限的数字。我修改了Pattern p = Pattern.compile("((zero|one|two|three|four|five|six|seven|eight|nine)\\s){1,}(add|sub|divide|multiply)(\\s(zero|one|two|three|four|five|six|seven|eight|nine)){1,}", Pattern.CASE_INSENSITIVE);,看起来很完美!你能验证一下吗?谢谢。
    • 只要将 '\\s' 设为 '\\s+' 以防万一字符串之间有多个空格,它不会失败。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多