我有一个 YYYY-MM-DD 日期格式的字符串。
var x = "I will need 2 pieces of that product 2020-01-16 04:38:09.After that i will need another 2020-01-16 04:38:09.";
我需要从 0 到第一个日期的开头对文本进行子串,因此整个字符串的输出应该是:
I will need 2 pieces of that product
老实说,因为我不知道 reg ex,所以我没有尝试任何事情。这就是我需要帮助的原因。 提前致谢
最佳答案
您可以使用正则表达式和组来实现此目的。
您可以注意到,我在这里使用了惰性运算符 ( *?
),这样,它只会匹配字符串的第一部分,即第一个日期。
^(.*?)(?:\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})
此正则表达式将匹配任何内容,直到看到日期格式 YYYY-MM-DD HH:mm:ss
。
比赛的第一组将是您正在寻找的。p>
在 Javascript 中,你可以像这样实现它:
let text = 'I will need 2 pieces of that product by 2020-11-26 2020-01-16 04:38:09.After that i will need another 2020-01-16 04:38:09.';
// notice here that we are using a non-capture group around the date
// because we do not need this part.
let regex = /^(.*?)(?:\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/;
let match = regex.exec(text);
// the first element of the array contains the whole matches,
// the second contains the first group.
console.log(match[1]);
关于javascript - 如何找到字符串中日期和时间的第一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59770433/