Javascript 如何使用正则表达式在特殊字符字符串中查找子字符串?
我有一根绳子Javascript 如何使用正则表达式在特殊字符字符串中查找子字符串?,javascript,regex,Javascript,Regex,我有一根绳子 element : 1 Description This is the description of item 1 ___________________ element : 2 Description This is the description of item 2 ______________________ 代码如下: var string = "element : 1\n\nDescription\nThis is the description of item
element : 1
Description
This is the description of item 1
___________________
element : 2
Description
This is the description of item 2
______________________
代码如下:
var string = "element : 1\n\nDescription\nThis is the description of item 1\n_________________\n\nelement : 2\n\nDescription\nThis is the description of item 2\n____________________________"
我希望能够使用regex从element:1
到element:2
提取子字符串(包括或仅限于此,现在不重要)
我使用了以下代码,但仍然不起作用:
var regexStr = /element : 1\s*\n(.*)element : 2/
var rx = new RegExp(regexStr, "i")
console.log(string.match(rx)); //null
你可以用
^element(?:(?!^element)[\s\S])+
使用多行修改器,请参见。
分解如下:
^element # match element at the start of a line
(?:
(?!^element) # neg. lookahead, making sure there's no element at the start of the line
[\s\S] # ANY character, including newlines...
)+ # ...as often as possible
你可以用
^element(?:(?!^element)[\s\S])+
使用多行修改器,请参见。
分解如下:
^element # match element at the start of a line
(?:
(?!^element) # neg. lookahead, making sure there's no element at the start of the line
[\s\S] # ANY character, including newlines...
)+ # ...as often as possible
在JavaScript中,
并不是每个字符都匹配。它匹配除行终止符之外的任何单个字符:\n
、\r
、\u2028
或\u2029
您可以改为使用[\s\s]
:
/element:1\s*\n([\s\s]*)element:2/
作为参考,
\s
表示任何空白字符,\s
是该字符的反义词。因此,[\s\s]
是“任何空格字符或非空格字符的字符”。。。因此,“任意字符”。在JavaScript中,
并不匹配每个字符。它匹配除行终止符之外的任何单个字符:\n
、\r
、\u2028
或\u2029
您可以改为使用[\s\s]
:
/element:1\s*\n([\s\s]*)element:2/
作为参考,
\s
表示任何空白字符,\s
是该字符的反义词。因此,[\s\s]
是“任何空格字符或非空格字符的字符”。。。因此,“任意字符”。它在正则表达式编辑器中工作得很好,但是你知道为什么它在这里不工作吗@YouMa:您需要添加多行
标志:../im
查看它在正则表达式编辑器中的工作情况,但是您知道它为什么在这里不工作吗@YouMa:您需要添加多行
标志:../im
请参见