使用regex从字符串中提取日期字符串

时间:2015-03-12 21:27:22

标签: javascript regex

我想从以下示例字符串中找到所有日期时间子字符串,该字符串以CAST(开头,以DateTime)结尾:

CAST(0x0000A21E000DD2C1 AS DateTime), 1, '98ac498b-89b6-434a-808d-020e82a59c82't, CAST(0x0000A20000C35DF7 AS DateTime), CAST(0x0000A20000C35DF7 AS DateTime), 1, 4, CAST(0x0000A20000C7558A AS DateTime)

修改

我想从字符串中找出所有单独的条目,例如CAST(0x0000A21E000DD2C1 AS DateTime)

谢谢, 阿赫亚

1 个答案:

答案 0 :(得分:0)

/(CAST\([^\)]* AS DateTime\))/g

匹配

CAST(0x0000A21E000DD2C1 AS DateTime)
CAST(0x0000A20000C35DF7 AS DateTime)
CAST(0x0000A20000C35DF7 AS DateTime)
CAST(0x0000A20000C7558A AS DateTime)

示例代码:

var re = /(CAST\([^\)]* AS DateTime\))/g; 
var str = 'CAST(0x0000A21E000DD2C1 AS DateTime), 1, \'98ac498b-89b6-434a-808d-020e82a59c82\'t, CAST(0x0000A20000C35DF7 AS DateTime), CAST(0x0000A20000C35DF7 AS DateTime), 1, 4, CAST(0x0000A20000C7558A AS DateTime)';
var m;

while ((m = re.exec(str)) != null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}

请参阅demo