【问题标题】:Javascript - match Regex for this date represenation [duplicate]Javascript - 匹配此日期表示的正则表达式 [重复]
【发布时间】:2023-03-24 00:06:01
【问题描述】:

我怎样才能写一个正确的正则表达式:

/Date(1518238800000)/ - matches

jdsjdsj - no match

2017/03/12 - no match

12 - no match

Date() - no match

/Date(1218238800000)/ - matches

到目前为止我所拥有的是:

var res = str.match(/Date(\d*)/g);

如何修改正则表达式才能正常工作?

【问题讨论】:

  • JSON 没有日期对象。
  • 已编辑,我的错!
  • 你应该转义括号Date\(\d+\)
  • JSON.stringify({date:new Date()}) 产生类似{"date":"2018-03-04T17:27:00.609Z"} 的东西。这通常是您在 JSON 中使用日期的方式。
  • @str 如果 OP 发布完整的字符串,也许你会很高兴。很可能 ASP.NET JSON 将 DateTime 序列化为以下格式 "/Date(1251877601000)/".

标签: javascript regex


【解决方案1】:

我假设您的字符串有点来自此​​处提到的 .NET 序列化程序

How to parse ASP.NET JSON Date format with GWT

How to parse JSON to receive a Date object in JavaScript?

其中一个答案具有您可能想要使用的 reviver 功能。

如果不是,那么正则表达式将需要转义括号:

var str = '{ "date": "/Date(1218238800000)/" }'
var re = /Date\((\d*)\)/g // escaping the () from the date and capture the number
res = re.exec(str);

console.log(res[1])

更多日期并创建日期对象:

var str = '{ "date1": "/Date(1218238800000)/", "date2": "/Date(1218248800000)/" }'
var re = /Date\((\d*)\)/g // escaping the () from the date and capture the number

while (res = re.exec(str)) {
  var date = +res[1]; // convert
  console.log(new Date(date)) 
}

【讨论】:

  • 但这不是 JSON。
  • 但可能是 OP 的意思
  • 我们不应该鼓励这样的事情。无论是术语还是使用“JSON”都是完全错误的。
  • @str 这样的东西有很多名字。可能是.NET的输出stackoverflow.com/questions/4511705/…
  • 但它仍然不是有效的 JSON。 { "date": "Date(1218238800000)" } 会。
【解决方案2】:

你需要像这样转义特殊字符:

let regex = /\/Date\(\d+\)\//g;
console.log(regex.test("/Date(123455)/"), //true
  regex.test("Date()"), //false
  regex.test("afdjkh"), //false
  regex.test("/Date(38457843)/")) //true

【讨论】:

    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多