正则表达式匹配字符串零次或一次 [英] Regex match zero or one time a string

查看:600
本文介绍了正则表达式匹配字符串零次或一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个匹配此字符串 {Date HH:MM:ss} 的正则表达式,但诀窍是:HH、MM 和 ss 是可选的,但它必须是HH",而不仅仅是";H"(同样的事情适用于 MM 和 ss).如果单个H"显示,该字符串不应该匹配.

I'm trying to make a Regex that matches this string {Date HH:MM:ss}, but here's the trick: HH, MM and ss are optional, but it needs to be "HH", not just "H" (the same thing applies to MM and ss). If a single "H" shows up, the string shouldn't be matched.

我知道我可以使用 H{2} 来匹配 HH,但我似乎无法使用该功能加上 ? 来匹配零次或一次(零是因为它是可选的,而一最大时间).

I know I can use H{2} to match HH, but I can't seem to use that functionality plus the ? to match zero or one time (zero because it's optional, and one time max).

到目前为止我正在这样做(这显然不起作用):

So far I'm doing this (which is obviously not working):

Regex dateRegex = new Regex(@"\{Date H{2}?:M{2}?:s{2}?\}");


下一个问题.现在我有了第一个字符串的匹配项,我只想取 HH:MM:ss 部分并将它放在另一个字符串中(这将是 TimeStamp 对象的格式).


Next question. Now that I have the match on the first string, I want to take only the HH:MM:ss part and put it in another string (that will be the format for a TimeStamp object).

我使用了相同的方法,如下所示:

I used the same approach, like this:

Regex dateFormatRegex = new Regex(@"(HH)?:?(MM)?:?(ss)?");

但是当我在{Date HH:MM}"上尝试时;我没有得到任何匹配.为什么?

But when I try that on "{Date HH:MM}" I don't get any matches. Why?

如果我添加这样的空格 Regex dateFormatRegex = new Regex(@" (HH)?:?(MM)?:?(ss)?");,我有结果,但我不想要空间...我认为第一个括号需要转义,但是 \( 在这种情况下不起作用.我猜是因为它不是要匹配的字符串的一部分的括号,而是一个关键字符.

If I add a space like this Regex dateFormatRegex = new Regex(@" (HH)?:?(MM)?:?(ss)?");, I have the result, but I don't want the space... I thought that the first parenthesis needed to be escaped, but \( won't work in this case. I guess because it's not a parenthesis that is part of the string to match, but a key-character.

推荐答案

(H{2})? 匹配零个或两个 H 字符.

(H{2})? matches zero or two H characters.

但是,在您的情况下,写两次会更具可读性:

However, in your case, writing it twice would be more readable:

Regex dateRegex = new Regex(@"\{Date (HH)?:(MM)?:(ss)?\}");

除此之外,请确保没有任何功能可用于您尝试执行的任何操作.解析日期非常普遍,大多数编程语言在其标准库中都有函数——我几乎打赌 .NET 也有这样的函数.

Besides that, make sure there are no functions available for whatever you are trying to do. Parsing dates is pretty common and most programming languages have functions in their standard library - I'd almost bet 1k of my reputation that .NET has such functions, too.

这篇关于正则表达式匹配字符串零次或一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆