0

我试图掌握正则表达式语法。有谁知道我可以如何进行以下工作?

    // if there is already a decimal place in the string ignore
    String origString = txtDisplay.getText();

    Pattern pattern = Pattern.compile("/\\./");

    //pattern = 
    if(pattern.matcher(origString)){
        System.out.println("DEBUG - HAS A DECIMAL IGNORE");
    }
    else{
        System.out.println("DEBUG - No Decimal");
    }
4

1 回答 1

1

Java 正则表达式不需要模式分隔符;即它们在模式的开头和结尾不需要/和斜线,否则它们将被逐字解释。/

您需要将模式更改为:

\\.

然后你可以检查是否有这样的匹配:

Matcher matcher = pattern.marcher(origString);
if(matcher.find()){
    System.out.println("DEBUG - HAS A DECIMAL IGNORE");
}
else{
    System.out.println("DEBUG - No Decimal");
}

但如果您想检查字符串是否包含点或任何其他字符串文字,您可以使用:

bool doesItContain = origString.indexOf('.') != -1;

whereindexOf()将任何字符串作为参数。

于 2013-10-10T15:22:22.440 回答