从字符串中提取日期 [英] Extracting a date from string

查看:185
本文介绍了从字符串中提取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字符串中创建一个日期提取器,以捕捉所有YouTube视频的音乐会。许多视频标题格式如下:

I'm trying to create a date extractor from a string to be a catch all on YouTube videos for concerts. Many video titles are formatted as such:

PHISH Reba Comcast Center Hartford CT. 6/18/2010
Phish - It's Ice - November 30, 1991
PHISH - 11.30.91 I didn't know
Phish/Worcester,MA 12-31-91 Llama
Phish: Tube / Runaway Jim [HD] 2011-01-01 - New York, NY
Phish - Stash (Live) 12.29.93

这些只是其中的几个例子。基本上,日期可以是: MM-DD-YYYY MM-DD-YY YY-MM-DD 等等。每个MM和DD可以是1或两个字符。每个YYYY可以是2或4个字符。 - 角色因期间,短划线到斜杠而异,可以通过简单的 /.?/ 在正则表达式中。

Those are just a few of the examples. Basically dates can be anything from: MM-DD-YYYY to MM-DD-YY to YY-MM-DD etc. Each MM and DD can be 1 or two characters. Each YYYY can be 2 or 4 characters. The - character varies from a period, to a dash, to a slash and can be fixed by a simple /.?/ in Regex.

我开始通过删除空格,然后在字符串上运行这个简单的正则表达式:

I began by stripping the whitespace and then running this simple Regex on the strings:

str.replace((new RegExp(' ', 'g')), '').match(/(([0-9]{1,4}).?([0-9]{1,2}).?([0-9]{1,4}))/)

// to highlight the regex:
// (([0-9]{1,4}).?([0-9]{1,2}).?([0-9]{1,4}))

这似乎工作得很好,但是我也必须包括这个数字是年份,即月,日等的逻辑。同时检测到错误的肯定。

This seems to work pretty well, but I also have to include the logic around which number is the year, which is the month, day, etc. along with detecting false positives.

此外,虽然我不希望能够检测到11月2日为11/2,这将是很酷:)

Also, while I don't expect to be able to detect "November 2" as 11/2, that would be cool :)

有人可以推我一点还是建议任何解决方案?我不想使用图书馆...我宁愿为此写一些特定的代码,因为它不是非常复杂的。感谢

Can anyone push me forward a bit or suggest any solutions? I don't want to use a library... I'd rather write specific code to this as it's not terribly complicated. Thanks

这是一个测试环境(打开您的控制台查看结果),以便您轻松播放数据。 http://jsfiddle.net/ZNLxW/4/

Here's a testing environment (open your console to see results) so you can play with the data easily. http://jsfiddle.net/ZNLxW/4/

推荐答案

这是我的尝试(使用 jsfiddle

Here is my attempt (with jsfiddle)

function formatDate(date) {
  function lz(value,w) {
    value = value.toString();
    return "0000".slice(4-w + value.length) + value;
  }
  return [
    lz(date.getFullYear(),4),
    lz(date.getMonth()+1,2),
    lz(date.getDate(),2)
  ].join('-');
}

//RegExp with support for short (XdYdZ) and long (month_in_text day, year)
var reDate = new RegExp([
  '(?:', // Short format
    '\\b',
    '(\\d{4}|\\d{1,2})',    // field.short_value_1
    '\\s*([./-])\\s*',      // field.short_del_1
    '(\\d{1,2})',           // field.short_value_2
    '\\s*([./-])\\s*',      // field.short_del 2
    '(\\d{4}|\\d{1,2})',    // field.short_value_3
    '\\b',
  ')|(?:', // Long format
    '\\b',
    '(',                    // field.long_month
    'jan(?:uary)?|',
    'feb(?:ruary)?|',
    'mar(?:ch)?|',
    'apr(?:il)?|',
    'may|',
    'jun(?:e)?|',
    'jul(?:y)?|',
    'aug(?:ust)?|',
    'sep(?:tember)?|',
    'oct(?:ober)?|',
    'nov(?:ember)?|',
    'dec(?:ember)?',
    ')',
    '\\s+',                 // required space
    '(\\d{1,2})\\b',        // field.long_date
    '\\s*',                 // optional space
    ',?',                   // optional delimiter
    '\\s*',                 // optinal space
    '(\\d{4}|\\d{2})\\b',   // field.long_year
  ')'
].join(''),'i');


//Month names, must be 3 chars lower case.
//Used to convert month name to number.
var  monthNames = [
  'jan', 'feb', 'mar', 'apr', 'may', 'jun',
  'jul','aug', 'sep', 'oct', 'nov', 'dev'
];


var extractDateFromString = function(str) {
    var m = str.match(reDate);
    var date;
    if (m) {
      var idx=-1;
      //Convert array form regexp result to named variables.
      //Makes it so much easier to change the regexp wihout
      //changing the rest of the code.
      var field = {
        all : m[++idx],
        short_value_1 : m[++idx],
        short_del_1 : m[++idx],
        short_value_2 : m[++idx],
        short_del_2 : m[++idx],
        short_value_3 : m[++idx],
        long_month : m[++idx],
        long_date : m[++idx],
        long_year : m[++idx]
      }

      //If field.long_month is set it is a date formated with named month
      if (field.long_month) {
        var month = monthNames.indexOf(
            field.long_month.slice(0,3).toLowerCase()
        );
        // TODO: Add test for sane year
        // TODO: Add test for sane month
        // TODO: Add test for sane date
        date = new Date(field.long_year,month,field.long_date);
      } else {
        // Short format: value_1 del_1 value_2 del_2 value_3
        var year, month, day;

        if (field.short_del_1 != field.short_del_2) {
          if (
            field.short_del_1 === '/' &&
            field.short_del_2 === '-'
          ) {
            // DD/MM-YYYY
            year = field.short_value_3;
            month = field.short_value_2;
            day = field.short_value_1;
            console.log('DMY',field.all,+year,+month,+day);
          } else {
            // TODO: Add other formats here.
            // If delimiters don't match it isn't a sane date.
            console.log('different delimiters');
          }
        } else {
          // assmume YMD if
          //   (delimiter = '-' and value_3 < 31)
          //   or (value_1 > 31) 
          if (
            (field.short_del_1 == '-' || field.short_value_1 > 31)
            && (field.short_value_3 < 32)
           ) {
            // YMD
            year = field.short_value_1;
            month = field.short_value_2;
            day = field.short_value_3;
            console.log('YMD',field.all,+year,+month,+day);
          } else {
            // MDY
            year = field.short_value_3;
            month = field.short_value_1;
            day = field.short_value_2;
            console.log('MDY',field.all,+year,+month,+day);
          }
        }

        if (year !== undefined) {
          year = +year; //convert to number
          //Handle years without a century 
          //year 00-49 = 2000-2049, 50-99 = 1950-1999
          if ( year < 100) {
            year += year < 50 ? 2000:1900;
          }
          date = new Date(year,+month-1,+day);
        }
      } 
    }

    var div = document.createElement('div');
    div.className = date ? 'pass' : 'fail';
    div.appendChild(document.createTextNode(date?formatDate(date):'NaD'));
    div.appendChild(document.createTextNode(' ' + str));
    document.body.appendChild(div);    
}
for (var i = 0; i < dates.length; i++) {
    extractDateFromString(dates[i].name)
}

更新:调整长格式的正则表达式(添加\b)

Updated: Tweaked the regexp for long format (added \b)

更新:再次调整regexp。没有更多的3位数字段。 (1,2或4)

Updated: Tweaked the regexp again. No more 3 digit fields. (either 1, 2 or 4)

这篇关于从字符串中提取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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