如何检查字符串中是否有时间?

时间:2015-09-02 19:23:27

标签: java android regex

我试图检查String是否包含时间,12或24小时格式,使用此正则表达式:.*([01]?[0-9]|2[0-3]):[0-5][0-9].*并使用String.matches(),但它没有&#39似乎工作。我做错了吗?

此外,我知道String.matches()的工作方式不同String.contains(),但我读到在正则表达式的开头和结尾添加.*会使其行为方式来自here

如果有人能帮助我,我真的很感激!

编辑:我尝试检查字符串中是否存在时间的示例就像是,"伦敦当前时间是下午6:00,多伦多的时间是多少? ",它将返回true,因为下午6:00在String内。

4 个答案:

答案 0 :(得分:2)

我使用Pattern和Matcher作为这个答案....

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

public class IsTimeInString {

    public static void main(String args[]){

         String string = args[0];
         System.out.println(String.format("Is there a time in here:(%1$s)", string));
         Pattern p = Pattern.compile(".*([01]?[0-9]|2[0-3]):[0-5][0-9].*");
         Matcher m = p.matcher(string);
         if(m.matches()){
             System.out.println("Yes");
         }else{
             System.out.println("No.");
         }
    }


}

示例输出......

$ java IsTimeInString "hi there"
Is there a time in here:(hi there)
No.

$ java IsTimeInString "hi there 2:15"
Is there a time in here:(hi there 2:15)
Yes

$ java IsTimeInString "hi there 14:15"
Is there a time in here:(hi there 14:15)
Yes

答案 1 :(得分:1)

以下是您可以使用的正则表达式:

String pattern = "(?i).*\\b(?:(?<twelve>(?:0?[0-9]|1[0-2]):[0-5][0-9](?::[0-5][0-9])?[ ]*[ap]\\.?m\\.?)|(?<twfour>(?:[01]?[0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?))\\b.*";
String str = "The current time in London is 6:00 PM, what is the time in Toronto?";
System.out.println(str.matches(pattern);

故障:

(?i)       # turning on case-insensitive matching
 .*        # match anything in the beginning
  \\b      # match a word boundary
  (?:      # Below is a 12 hour format with AM/PM
    (?<twelve>(?:0?[0-9]|1[0-2]):[0-5][0-9](?::[0-5][0-9])?[ ]*[ap]\\.?m\\.?)
    |      # Below is 24 hour format
    (?<twfour>(?:[01]?[0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?)
  )
 \\b
.*

请参阅IDEONE demo

答案 2 :(得分:0)

试试这个

    String myString = "The current time in London is 6:00 PM";
    StringTokenizer st = new StringTokenizer(myString, "\\s+");
    SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
    SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
    Date timeShort, timeLong;
    while(st.hasMoreTokens())
    {
        String possibleTime = st.nextToken();
        if(possibleTime.matches(".*\\d.*"))
        {
            System.out.println(possibleTime.trim());
            try {
                timeShort = sdf.parse(possibleTime);
                System.out.println("TIME: " + timeShort);
            } catch (ParseException e) {
                // Not AM/PM Time
            }
            try {
                timeLong = sdf1.parse(possibleTime);
                System.out.println("TIME: " + timeLong);
            } catch (ParseException e) {
                // Not normal Time
            }
        }
    }

结果是

  

下午6:00

     

时间:周一1月1日18:00:00 CET 1970

后来作为反驳证据尝试用JavaTime解析它

答案 3 :(得分:0)

更新:在AM / PM可选之前留出空间,因为您有时会看到ls /lib/modules/`uname -r`/kernel/net/ipv4/ ah4.ko inet_diag.ko ipip.ko netfilter udp_diag.ko xfrm4_mode_tunnel.ko esp4.ko ipcomp.ko ip_tunnel.ko tcp_diag.ko xfrm4_mode_beet.ko xfrm4_tunnel.ko gre.ko ip_gre.ko ip_vti.ko tunnel4.ko xfrm4_mode_transport.ko 。还添加了单词边界检查。

假设您可能想要多次进行检查,最好预编译正则表达式。

9:45am

注意&#34;后面没有&#39;上午&#39;或者&#39;下午&#39;&#34;,否则它会匹配String timeExpr = "\\b" + // word boundary "(?:[01]?[0-9]|2[0-3])" + // match 0-9, 00-09, 10-19, 20-23 ":[0-5][0-9]" + // match ':' then 00-59 "(?! ?[ap]m)" + // not followed by optional space, and 'am' or 'pm' "\\b" + // word boundary "|" + // OR "\\b" + // word boundary "(?:0?[0-9]|1[0-1])" + // match 0-9, 00-09, 10-11 ":[0-5][0-9]" + // match ':' and 00-59 " ?[ap]m" + // match optional space, and 'am' or 'pm' "\\b"; // word boundary Pattern p = Pattern.compile(timeExpr, Pattern.CASE_INSENSITIVE);

你可以这样测试:

17:00 PM

或者实际提取时间的更复杂的例子:

String str = "The current time in London is 6:00 PM, what is the time in Toronto?";
if (p.matcher(str).find()) {
    System.out.println("Has time");
} else {
    System.out.println("Has no time");
}

输出同时运行:

String str2 = "When it is 6:00 PM in London, is it 14:00 in Toronto?";
Matcher m = p.matcher(str2);
if (! m.find())
    System.out.println("Has no time");
else
    do {
        System.out.println("Found time: " + m.group());
    } while (m.find());