如何在字符串中找到时间值(类似#:#)

时间:2022-08-14 19:25:21

Looking for a way to find anything that looks like a time value, such as 1:00 or 2:30 anywhere in a given string. I'd rather not scan the whole string for

寻找一种方法来查找任何看起来像时间值的东西,比如在给定字符串的任何地方的1:00或2:30。我宁愿不扫描整个字符串

If String.Mid(myString,i,4) Like "#:##" Then ...

if there is a better way to accomplish the same thing.

如果有更好的方法来完成同样的事情。

An occassional false positive is okay, so if I get 0:99 identified as a time value, there is no harm in that, and finding the 2:00 part of the time value 12:00 is fine too -- pointing at the character 2 instead of the character 1 causes no problems. And for this application, finding other separators besides the colon isn't needed.

偶尔的假阳性是可以的,所以如果我将0:99作为时间值,这没有什么害处,找到时间值12:00的2:00部分也是可以的——指向字符2而不是字符1不会造成任何问题。对于这个应用程序,除了冒号之外,不需要找到其他分隔符。

Is a RegEx the best way to search for this sort of pattern, or is another approach more efficient?

RegEx是搜索这种模式的最佳方式,还是另一种更有效的方法?

Thanks!

谢谢!

1 个解决方案

#1


2  

A RegEx is probably the most straightforward solution for what you described.

RegEx可能是您所描述的最直接的解决方案。

Dim stringToMatch = "The time is 1:00 or maybe 13:01 or possibly 27:03 or 4:99 or part of 103:17, but not 22:7"
Dim matcher = New Regex("[0-9]{1,2}:[0-9]{2}")
Dim matches = matcher.Matches(stringToMatch)
For Each match As Match In matches
    Console.WriteLine("Found match {0} at position {1}", match.Value, match.Index)
Next match

From there, it's simple to alter the RegEx pattern to better suit your needs, or to examine the Match objects to determine what was matched, at what index in the original string.

从这里开始,可以简单地修改RegEx模式以更好地满足您的需要,或者检查Match对象以确定在原始字符串的哪个索引处匹配了什么。

#1


2  

A RegEx is probably the most straightforward solution for what you described.

RegEx可能是您所描述的最直接的解决方案。

Dim stringToMatch = "The time is 1:00 or maybe 13:01 or possibly 27:03 or 4:99 or part of 103:17, but not 22:7"
Dim matcher = New Regex("[0-9]{1,2}:[0-9]{2}")
Dim matches = matcher.Matches(stringToMatch)
For Each match As Match In matches
    Console.WriteLine("Found match {0} at position {1}", match.Value, match.Index)
Next match

From there, it's simple to alter the RegEx pattern to better suit your needs, or to examine the Match objects to determine what was matched, at what index in the original string.

从这里开始,可以简单地修改RegEx模式以更好地满足您的需要,或者检查Match对象以确定在原始字符串的哪个索引处匹配了什么。