简体   繁体   English

正则表达式:匹配 JS 中的新行或行尾或空格

[英]Regex: matches to new line or end of line or space in JS

I wanted to extract :privacy and :date from the example string below.我想从下面的示例字符串中提取:privacy:date

I wanted to have a regex constraint that describes that a :[^:\s]+ block (eg :privacy or :date ) can only be ended by a space \s or a newline \n or a end of string $ (so I will be able to have a rule to logically split these blocks in the later steps).我想要一个正则表达式约束来描述:[^:\s]+块(例如:privacy:date )只能由空格\s或换行符\n或字符串结尾$结束(所以我将能够有一个规则在后面的步骤中逻辑地拆分这些块)。

So I simply put (?:$|\n|\s) at the end of the regex, but I doesn't work for me (the 3rd regex below).所以我只是把(?:$|\n|\s)放在正则表达式的末尾,但我不适合我(下面的第三个正则表达式)。 I double checked that it does work when I separately put \s or $ (the 1st and 2nd regex below), now I have no idea how I can implement the thing.当我分别放置\s$ (下面的第一个和第二个正则表达式)时,我仔细检查了它是否有效,现在我不知道如何实现这个东西。 Thanks for your help.谢谢你的帮助。

'note::tmp hogehoge. :privacy :date'.match(/\s:[^:\s]+\s/g)
(1) [' :privacy ']

'note::tmp hogehoge. :privacy :date'.match(/\s:[^:\s]+$/g)
(1) [' :date']

'note::tmp hogehoge. :privacy :date'.match(/\s:[^:\s]+(?:$|\n|\s)/g)
(1) [' :privacy ']

You can use below regex pattern to match a block pattern:[^:\s+]+ ended by a space \s or a newline \n or a end of string $您可以使用下面的正则表达式模式来匹配块模式:[^:\s+]+ 以空格 \s 或换行符 \n 或字符串结尾结尾 $

/((:[^:\s+]+)(?:[\s\n]))|(:[^:\s+]+)(?:[\s\n])?$/gm

(?:[\s\n]) - will check if the block is being followed by a space or a new line
(:[^:\s+]+)(?:[\s\n])?$ - will check if the block is at the end of string or not.

you can also use lookforward technique to achieve the same result您还可以使用前瞻技术来实现相同的结果

(:[^:\s+]+)(?=\s|\n|$)

In your pattern \s:[^:\s]+\s you are matching the leading and the trailing whitespace chars.在您的模式\s:[^:\s]+\s中,您正在匹配前导和尾随空白字符。

What you might do is assert a whitespace boundary using (?!\S) to the right.您可能会做的是在右侧使用(?!\S)断言空白边界。

To get the value without the leading whitespace char, you can use a capture group.要获取没有前导空格字符的值,您可以使用捕获组。

\s(:[^:\s]+)(?!\S)

Regex demo正则表达式演示

 const s = "note::tmp hogehoge. :privacy:date"; const regex = /\s(:[^:\s]+)(?;\S)/g. const result = Array.from(s,matchAll(regex); m => m[1]). console;log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM