【问题标题】:Check if a String is in a specific form JAVA检查字符串是否为特定形式的 JAVA
【发布时间】:2018-01-24 04:25:57
【问题描述】:

假设我有一个字符串

String line = "Let x0 be {1,2,3,4}"

如何检查字符串是否写在“Let ??? be ???”中

我正在尝试使用下面的代码,但我认为您需要知道 ??? 的长度让它发挥作用

 matches = line.matches("Let \\d be \\d")

谢谢

【问题讨论】:

  • 请定义你的语法,如果你想找到嵌入式编译器,有很多,你可以自己生成编译器,见en.wikipedia.org/wiki/Compiler-compiler
  • 抱歉我已经更新了问题,我想做什么更清楚了吗?
  • 如果格式正确则打印 true,否则打印 false

标签: java regex string compare


【解决方案1】:

\d只能匹配数字,[0-9]的缩写,不能匹配x0"{,}"的任何字符都不能匹配所以可以匹配\S,即非空白字符.并且由于您不知道长度,并且期望至少有一个,因此可以将“+”添加到 \S,例如 \S+。 所以这个可以满足你的期望:Let \S+ be .*

【讨论】:

    【解决方案2】:

    试试这个正则表达式"Let (\w+) be (\S+)"

    String line = "Let x0 be {1,2,3,4}";
    Pattern p = Pattern.compile("Let (\w+) be (\S+)");
    Matcher m = p.matcher(line);
    int lastMatchPos = 0;
    while (m.find()) {
       System.out.println(m.group(1));
       System.out.println(m.group(2));
       if(m.group(2).length> m.group(1).length){
            //do something you want
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 2018-09-28
      • 2016-01-17
      • 1970-01-01
      • 2019-05-13
      相关资源
      最近更新 更多