繁体   English   中英

如何用正则表达式在特殊字符字符串中找到子字符串?

[英]How to find a substring within a string of special characters with 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 1\n_________________\n\nelement : 2\n\nDescription\nThis is the description of item 2\n____________________________"

并且我希望能够使用正则表达式提取从element : 1element : 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])+

使用多行修饰符,请参阅regex101.com上的演示


分解说:

 ^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\
\


您可以改为[\\s\\S]

/element : 1\\s*\\n([\\s\\S]*)element : 2/

作为参考, \\s表示任何空白字符,而\\S是该字符的倒数。 因此[\\s\\S]是“是空白字符或不是空白字符的任何字符” ...因此是“任何字符”。

暂无
暂无

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

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