Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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?

like image 917
AnApprentice Avatar asked Mar 09 '11 00:03

AnApprentice


People also ask

How do I use a question mark in regex?

A question mark ( ? ) immediately following a character means match zero or one instance of this character . This means that the regex Great!? will match Great or Great! .

What is preceding token in regex?

asterisk or star ( * ) - matches the preceding token zero or more times. For example, the regular expression ' to* ' would match words containing the letter 't' and strings such as 'it', 'to' and 'too', because the preceding token is the single character 'o', which can appear zero times in a matching expression.


2 Answers

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

like image 63
kindall Avatar answered Oct 04 '22 01:10

kindall


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

(?:at)?
like image 38
Andrew Grimm Avatar answered Oct 04 '22 01:10

Andrew Grimm