繁体   English   中英

如何编写忽略部分匹配的正则表达式?

[英]How to write a regex which ignores a partial match?

想象一下这个降价文件:

...

## Questions heading
### Question sub-heading
- some question
- some question
### Question sub-heading
- some question

## Next section heading
- blah
- blah

## Another section heading
- blah
- blah

我需要能够提取“ 问题”部分中的所有问题 ,有时可能包括“ 问题”子标题

我的正则表达式仅在sub-heading doesn't exist时才起作用。 这是我当前的正则表达式: ##\\sQuestions([\\s\\S]*?)##对于上面的示例,它将返回以下内容:

## Questions heading
##

我需要它来返回两个主要标题之间的整个部分。 看起来应该像这样:

### Question sub-heading
- some question
- some question
### Question sub-heading
- some question

我需要忽略又是###子标题,因为它们不是主要部分的标题,并继续匹配,直到下一个主要部分的标题开始为止,这被称为##

您可以使用负前瞻匹配\\n##只时,它后面没有其他#通过追加(?!#)

##\\sQuestions([\\s\\S]*?)\\n##(?!#)

请注意,您需要匹配\\n##而不是## 不匹配换行符,正则表达式仍可以匹配### :第一个#将作为[\\s\\S]一部分进行匹配。

这应该可以解决问题,我并不是说它很漂亮,但是可以使用:

/^##\s*Questions.*?\n([^]*?)^##[^#]/m

测试:

var match = `## Questions heading
### Question sub-heading
- some question
- some question
### Question sub-heading
- some question

## Next section heading
- blah
- blah

## Another section heading
- blah
- blah`.match(/^##\s*Questions.*?\n([^]*?)^##[^#]/m);
if (match) {
  console.log(match[1]);
}

它依赖于##在行的开头。

分解:

/
  ^##\s*Questions.*?\n # Match "## Questions ...\n"
  ([^]*?)              # Match anything including newline
  ^##[^#]              # Match "## ..."
/m                     # Make `^` and `$` work on each line instead of all input

暂无
暂无

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

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