您好我正在尝试使用正则表达式从html获取文本
([a-zA-Z0-9\:\[\]\40\.\'\,\?\"\&\(\/\)\-\“\”\’\@]){600,} // let's say the example is more than 600 letters
问题是
我想添加\n
两个我的正则表达式,但最多两个换行符,例如
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis dictum metus ipsum, ut hendrerit sem consectetur quis.
\n
Nunc tincidunt mi nisl, in lobortis diam pulvinar vel. Nulla at tempus enim, sit amet viverra nisl.
\n
Nunc tincidunt mi nisl, in lobortis diam pulvinar vel. Nulla at tempus enim, sit amet viverra nisl.
\n
\n
Not this
它只匹配前3行,所以我得到像
这样的东西Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis dictum metus ipsum, ut hendrerit sem consectetur quis.
\n (ok)
Nunc tincidunt mi nisl, in lobortis diam pulvinar vel. Nulla at tempus enim, sit amet viverra nisl.
\n (ok still one)
.....
\n (ok still one)
\n (ups its more than one then stop a group)
结果将是
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis dictum metus ipsum, ut hendrerit sem consectetur quis.
Nunc tincidunt mi nisl, in lobortis diam pulvinar vel. Nulla at tempus enim, sit amet viverra nisl.
Nunc tincidunt mi nisl, in lobortis diam pulvinar vel. Nulla at tempus enim, sit amet viverra nisl.
答案 0 :(得分:2)
这是negative lookahead assertion的作业:
[a-zA-Z0-9: \[\].',?"&(/)“”’@-]{600,}\n\n(?!\n)
只有在该匹配后找不到其他换行符时,才会匹配600个或更多允许的字符,再加上两个换行符。
答案 1 :(得分:0)
可能的解决方案是。
([a-zA-Z0-9\:\[\]\40\.\'\,\?\"\&\(\/\)\-\“\”\’\@]\n?){600,}
两件事:
新行不会计入字符数限制(在您的情况下为600)
这不适用于您的示例,因为它少于600个字符(大约有330个字符)。