如何在 Ruby 中使正则表达式的一部分成为可选的? [英] How do I make part of a regular expression optional in Ruby?

查看:30
本文介绍了如何在 Ruby 中使正则表达式的一部分成为可选的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

匹配以下内容:

On Mar 3, 2011 11:05 AM, "mr person" 
wrote: 

我有以下正则表达式:

/(On.* (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2}, [12]\d{3}.* at \d{1,2}:\d{1,2} (?:AM|PM),.*wrote:)/m

有没有办法让 at 成为可选的?所以如果它很棒,如果不是,它仍然匹配吗?

Is there a way to make the at optional? so if it's there great, if not, it still matches?

推荐答案

好的.把它放在括号里,在它后面打一个问号.包括其中一个空格(否则,如果缺少at",您将尝试匹配两个空格.) (at )? (或按照其他人的建议,(?:在 )? 以避免它被捕获).

Sure. Put it in parentheses, put a question mark after it. Include one of the spaces (since otherwise you'll be trying to match two spaces if the "at" is missing.) (at )? (or as someone else suggested, (?:at )? to avoid it being captured).

这篇关于如何在 Ruby 中使正则表达式的一部分成为可选的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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