我有以下情况:
时间格式和一些描述,由分隔符-
分隔(如下所示)
00:00 - Hello 元素
我使用下面的正则表达式来检测匹配
/((?:\d{2,}:)?(?:[0-5]\d):(?:[0-5]\d)(\s?-.\w+))/g;
它仅匹配空格后的“00:00 - Hello”,但未匹配。这是它的演示 https://regex101.com/r/omUEHy/1
此外,如果字符串在同一行中多次匹配,它应该可以工作。
如果我有像 00:50 - Hello element 01:50 - Poetry
这样的文本。它应该返回 00:50 - Hello element
和 01:50 - Poetry
最佳答案
提供的正则表达式... /\d{2}:\d{2}\s+.*?(?=\s+\d{2}:|\s+$)/g
...利用 positive lookahead ... (?=\s+\d{2}:|\s+$)
(空白序列两位数字和冒号或空白序列和字符串结尾)...为了定义终止任何字符的惰性/非贪婪匹配 ... .*?
... 遵循 ... \d{2}:\d{ 的开头匹配序列2}\s+
.
const multilineSample =
`00:50 - Hello element 01:50 - Poetry 00:50 - Hello element and another element 01:50
- Poetry 00:50 - Hello element and another element 01:50 - Poetry and prose 00:50 - Hello element 01:50 - Poetry `;
const regXTimeAndEntry = /\d{2}:\d{2}\s+.*?(?=\s+\d{2}:|\s+$)/g;
console.log(
multilineSample.match(regXTimeAndEntry)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
关于javascript - 正则表达式匹配分隔符后的任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72052297/