Java: check to see if a String has 1 or more times in it

后端 未结 2 1814
春和景丽
春和景丽 2021-01-23 03:24

I\'m parsing out text from a file and trying to look at the times. I first need to check if there are times in the text. The only consistent pattern in the text is that all time

相关标签:
2条回答
  • 2021-01-23 03:53

    To find such a pattern you're best off using a regular expression, something like this:

    Pattern timePattern = Pattern.compile("[0-2][0-9]:[0-5][0-9]");
    

    Now you can create a Matcher to see whether this Pattern is found within a CharSequence, like this:

    Matcher timeMatcher = timePattern.matcher(textWithTime);
    while(timeMatcher.find()) {
        System.out.println("Found time " + timeMatcher.group() + " in the text!";
    }
    

    Have a look at the API for java.util.regex to see the other methods which Pattern and Matcher provide. Regular expressions are very powerful.

    0 讨论(0)
  • 2021-01-23 03:56

    matches checks if entire string is matched by used regex and since only part of this regex can be matched you are getting false as result.

    Way around would be adding .* at start and end of your regex to let it match parts before or after matched substring.

    textWithTime.matches(".*\\d\\d?:\\d\\d.*");
    

    but this solution would have to iterate over all characters of strings to evaluate it.

    Better approach would be using find() method from Matcher class which will stop iterating after first match (or will return false in case when no match of regex could be found).

    Pattern p = Pattern.compile("\\d\\d?:\\d\\d");
    Matcher m = p.matcher(textWithTime);
    if (m.find()){
        System.out.println("MATCH");
    } else {
        System.out.println("NO MATCH");
    }
    
    0 讨论(0)
提交回复
热议问题