简体   繁体   中英

Ruby Regex: How to match (named) groups inside square brackets?

I'm trying to write a regex in Ruby that will parse various date/time formats. The entire regex looks like this:

/^(?<year>\d{4})\-(?<month>\d{2})\-(?<day>\d{2})(T(?<hour>\d{2})(:(?<minute>\d{2})(:(?<second>\d{2}(\.\d{1,3})?))?)?)?(?<offset>[+-]\d{2}:\d{2})?$/

I'm using named groups so that I can fetch the matching parts out of the match object just using the simple names like "year", "month", "day", etc. This regex is working fine, but let's focus on the "offset" at the end of this:

(?<offset>[+-]\d{2}:\d{2})?

The problem is that I'm trying to add the ability to interpret a "Z" on the end of the string to denote UTC time (aka Zulu Time). This "Z" should be mutually exclusive with the offset. Here's some of the ways I've tried it:

(?<offset>[Z([+-]\d{2}:\d{2})])?
(?<offset>[(Z)([+-]\d{2}:\d{2})])?
[(?<zulu>Z)(?<offset>[+-]\d{2}:\d{2})]?

None of these work. In the first two cases, it can interpret date strings ending in "Z", but it can no longer interpret date string ending with actual offsets like "-07:00". In the third case, the named groups "zulu" and "offset" are just totally missing from the match object.

I think this issue is because I'm trying use square brackets to denote [(ThisGroup)(OrThisGroup)]? but I don't think the regex engine appreciates having groups inside of square brackets. How do I tell the regex engine to allow and capture "group A or group B or neither, but not both"?

Square brackets are used for "exactly one of any of these characters" -- that's not what you need here. Pattern-level alternation is done via the | operator: (hello|goodbye) world will match either hello world or goodbye world .

(?<offset>Z|[+-]\d{2}:\d{2})?

Specifically to parse a datetime, though, I suggest preferring DateTime.parse (plus to_time , if you need a Time instance). And if that isn't sufficiently flexible, consider the chronic gem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM