【问题标题】:Why isn't my code detecting the digit in my string. I'm using regex为什么我的代码没有检测到字符串中的数字。我正在使用正则表达式
【发布时间】:2018-10-07 05:47:00
【问题描述】:

这是我的代码。我正在寻找我选择的单词中的任何数字,但是当我的查找器查看我的单词时它返回 false,但我的单词中显然有一个数字。

package payrollprinter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PayRollPrinter {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        String word = "7";

        // convert the string to a pattern
        Pattern wordPattern = Pattern.compile(word);

        // now I look for digits in my word
        Matcher finder = wordPattern.matcher("\\d");
        boolean b = finder.find();
        System.out.println(b);
    }

}

【问题讨论】:

  • mi.matcher(month);Pattern.compile("\\d");.matcher() 需要输入字符串,Pattern.compile 需要正则表达式模式。
  • 为什么要投反对票?这是一个很好的初学者问题。它具有最小、不完整和可验证的示例,具有预期行为以及观察到的行为有何不同。
  • 我同意@OleV.V。除了这可能是 RT*M。文档应该足以找到问题。但作为一个菜鸟,我也不是第一个打开文档的人;)

标签: java regex string character match


【解决方案1】:

正如 cmets 中已经说过的,您不小心交换了模式 \d 和单词 7

    String word = "7";

    // translate the pattern so Java can work with it
    Pattern wordPattern = Pattern.compile("\\d");

    // now I look for a digit in my word
    Matcher finder = wordPattern.matcher(word);
    boolean b = finder.find();
    System.out.println(b);

输出:

是的

【讨论】:

    猜你喜欢
    • 2013-01-18
    • 2019-10-04
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    相关资源
    最近更新 更多