开发者

How do I make part of a regular expression optional in Ruby?

To match the following:

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

I have the following regular expression:

/(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

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


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).


Don't forget (?:) to make sure the bracketed expression doesn't get captured

(?:at)?


Sure, you just need to group the optional part...

   (at )*

And, ok, I guess that will match at at at at, so you might want to just do:

   (at )?


Others got your answer. This is just an aside re: Regular Expressions.

When you say "conditions" in regular expressions, it refers to the regex language. Like any language, its a branch in code execution, but the code is a different regular expression path, the "code" of regular expressions.

So in psudo code: if (evaluation is true) do this regular sub-expression, else do this other sub-expression.

This conditional exists in advanced regular expression engines ... Perl.
Perl uses the most advanced regular expression engine that exists. In version 6 and beyond it will be an integral part of the language, where code and expression intermingle seamlessly.

Perl 5.10 has this construct:
(?(condition)yes-pattern|no-pattern).

Edit Just a warning that where Perl goes, every other language follows as far as regular expression.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜