java 一个字符串中有多少个点。(爪哇)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12082337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:31:58  来源:igfitidea点击:

How many dots are in a string. (Java)

javaregex

提问by 0gravity

So, I am working on a program in which I need to check if a string has more than one dot. I went and looked at the documentation for regexand found this:

所以,我正在开发一个程序,我需要检查一个字符串是否有多个点。我去看了看文档regex,发现了这个:

X{n,m}?  X, at least n but not more than m times

Following that logic I tried this:

按照这个逻辑,我尝试了这个:

mString = "He9.lo,"

if (myString.matches(".{1,2}?")){

    System.out.print("it works");
}

But that does not works (It does not gives any error, it just wont do what is inside the if). I think the problem is that is thinking that the dot means something else. I also looked at this question: regexbut is for php and I don't know how to apply that to java.

但这不起作用(它不会给出任何错误,它只是不会执行if. 我认为问题在于认为点意味着别的东西。我也看过这个问题:regex但适用于 php,我不知道如何将其应用于 java。

EDIT: Basically I want to know if a string contains more than one dot, for example:

编辑:基本上我想知道一个字符串是否包含多个点,例如:

He......lo (True, contains more than one), hel.llo (False, contains one), ..hell.o (True Contains more than one).

He......lo(真,包含多个),hel.llo(假,包含一个),..hell.o(真,包含多个)。

Any help would be appreciated.

任何帮助,将不胜感激。

回答by Jon Skeet

A dot in a regular expression means "any character". So if you want actual dotsyou need to escape it with a backslash - and then you need to escape the backslash within Java itself...

正则表达式中的点表示“任何字符”。所以如果你想要实际的点,你需要用反斜杠转义它 - 然后你需要在 Java 本身中转义反斜杠......

if (myString.matches("\.{1,2}?")){

Next you need to understand that matchestries to match the wholetext - it's not just trying to find the pattern withinthe string.

接下来,您需要了解matches尝试匹配整个文本 - 这不仅仅是尝试字符串中查找模式。

It's not entirely clear what your requirements are - is it just "more than one dot together" or "more than one dot anywhere in the text"? If it's the latter, this should do it:

尚不清楚您的要求是什么 - 只是“一起超过一个点”还是“文本中任何地方超过一个点”?如果是后者,应该这样做:

if (myString.matches(".*\..*\..*")) {

... in other words, anything, then a dot, then anything, then a dot, then anything - where the "anything" can be "nothing". So this will match "He..llo" and "H.e.llo", but not "He.llo".

... 换句话说,任何东西,然后是一个点,然后是任何东西,然后是一个点,然后是任何东西——其中“任何东西”可以是“无”。所以这将匹配“He..llo”和“Hello”,但不会匹配“He.llo”。

Hopefully that's what you want. If you literallyjust want "it must have .. in it somewhere" then it's easier:

希望这就是你想要的。如果你真的只是想要“它必须在某个地方有..”那么它更容易:

if (myString.contains(".."))

回答by Aleksander Blomsk?ld

As mentioned in the other answers, your regex contains a bug. You could either fix that (escape the dot), or use String.containsinstead:

正如其他答案中提到的,您的正则表达式包含一个错误。你可以解决这个问题(转义点),或者String.contains改用:

if (myString.contains("..")){
    System.out.print("it works");
}

This will match for two consecutive dots. If you're also looking for two dots anywhere in the string (like in the string "He.llo.") you could do

这将匹配两个连续的点。如果您还在字符串中的任何位置寻找两个点(如字符串“He.llo.”),您可以这样做

if(myString.indexOf('.', myString.indexOf('.') + 1) != -1) {
    System.out.print("it works"); //there are two or more dots in this string
}

回答by MadProgrammer

I think the other answers are better, however, just for a different perspective

我认为其他答案更好,但是,只是从不同的角度来看

if (myString.indexOf(".") != myString.lastIndexOf(".")) {
    // More then one dot...
}

回答by Nate Bosch

StringUtils.countMatchesmakes it more immediately obvious what is happening.

StringUtils.countMatches使正在发生的事情变得更加明显。

boolean multipleDots = StringUtils.countMatches( myString, "." ) > 1;

回答by Giedrius ?likas

this solution works perfectly for me if I want to check does the string has 2 dots. In other words it's a validation for URL

如果我想检查字符串是否有 2 个点,此解决方案非常适合我。换句话说,它是对 URL 的验证

private boolean isValid(String urlString) {
        try {
            String extensionValidator;
            extensionValidator = urlString.substring(urlString.lastIndexOf('.') + 1);
            URL url = new URL(urlString);

            if (urlString.indexOf('.', urlString.indexOf('.') + 1) != -1) {
                if (extensionValidator.length() >= 2 && urlString.contains(".")) {
                    return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
                }
            }

        } catch (MalformedURLException e) {

        }

        return false;
    }

回答by dosakiller

You need to use escape sequence characters for those characters which are already part of the regex metacharacters set

对于已经是正则表达式元字符集的一部分的字符,您需要使用转义序列字符

\ | ( ) [ { ^ $ * + ? . < >

\ | ( ) [ { ^ $ * + ? . < >

Since the "." character is also part of the meta characters set, You need to use "\." to match the string pattern with multiple "." characters.

由于“。” 字符也是元字符集的一部分,您需要使用“\”。匹配带有多个“.”的字符串模式 人物。

in this case myString.matches("\\.{1,2}?")

在这种情况下 myString.matches("\\.{1,2}?")

回答by Alex

You can use []or \to escape special characters, which the dot character .is, meaning any character.

您可以使用[]\来转义特殊字符,点字符.是指任何字符。

For example using brackets to escape it: myString.matches("[.]{1,2}?")

例如使用括号来转义它: myString.matches("[.]{1,2}?")