正则表达式匹配包含特定字符的句子中的所有空格

Regex match all spaces in sentences containing certain character

我正在寻找正确的正则表达式来匹配包含“->”的句子中的所有空格。

.*->.*\r? 

适用于 select 所有正确的句子,但我很难将它与 /s

联系起来

示例文本:我尝试重新格式化字幕文本。我需要从时间码中取出所有空格:

7
00: 00: 20,509 -> 00: 00: 25,059
on the data before and does not shy in front of radical solutions such as post privacy back.

8
00: 00: 25,159 -> 00: 00: 27,896
On his blog writes sower already since 2011

9
00: 00: 27,996 -> 00: 00: 31,784
on the impact of technology on society, politics and economy.

预期的结果是:

7
00:00:20,509->00:00:25,059
on the data before and does not shy in front of radical solutions such as post privacy back.

非常感谢!

根据您的示例,在正则表达式中有一些比 :(冒号和 space)更复杂的解决方案:

first one

((?:(?<\d:)|(?<=->)) | (?=->)) 将 select space 只有在 [0-9]:-> 或 space 紧接着 ->

A shorter one(但更防错):

((?:(?<=:|>)) | (?=->)) 思路同上,前瞻中交替进行。

The most exact one 与您的格式完全匹配,但需要替换为 --> 而不是什么都没有

(\d{2}:) (\d{2}:) ([0-9,]+) -> (\d{2}:) (\d{2}:) ([0-9,]+)