Java匹配一个正则表达式小数位

时间:2022-08-03 08:54:42

Im trying to get to grips with the regex syntax. Does anyone know how I can make the following work?

我试图掌握正则表达式的语法。有谁知道我怎么做以下工作?

    // 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");
    }

1 个解决方案

#1


1  

Java regular expressions don't need pattern delimiters; i.e. they don't need the / and / slashes at the start and end of the pattern or they will be interpreted literally.

Java正则表达式不需要模式分隔符;即,它们不需要在模式的开头和结尾处使用/和/斜杠,否则它们将按字面解释。

You need to change your pattern to:

您需要将模式更改为:

\\.

and then you can you can check if there is a match like this:

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

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

but in case you want to check if a string contains a dot or any other string literal you can just use:

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

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

where indexOf() takes as a parameter any string.

其中indexOf()将任何字符串作为参数。

#1


1  

Java regular expressions don't need pattern delimiters; i.e. they don't need the / and / slashes at the start and end of the pattern or they will be interpreted literally.

Java正则表达式不需要模式分隔符;即,它们不需要在模式的开头和结尾处使用/和/斜杠,否则它们将按字面解释。

You need to change your pattern to:

您需要将模式更改为:

\\.

and then you can you can check if there is a match like this:

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

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

but in case you want to check if a string contains a dot or any other string literal you can just use:

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

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

where indexOf() takes as a parameter any string.

其中indexOf()将任何字符串作为参数。