简体   繁体   English

正则表达式让我字符串,给定开始和结束

[英]Regex that gets me string, given beginning and end

I want to build a function with 3 parameters: 我想用3个参数构建一个函数:

var function = searchMyRegex(begin_marker, end_marker, text) { ... }

I need a RegExp that will give me certain string, given the beginning and end, but it will me the shortest version, meaning that neither the beginning nor the end will be in between the 2 markers 我需要一个RegExp,它可以给我一定的字符串(给定开始和结束),但是它是我的最短版本,这意味着开始和结束都不会在2个标记之间

For instance 例如

var text = "Lorem ipsum ipsum sit amet amet adipisicing elit"

If BEGIN is ipsum and END is amet , I want to get in return ipsum sit amet , not ipsum ipsum sit amet amet 如果BEGIN是ipsum而END是amet ,我想返回ipsum sit amet ,而不是ipsum ipsum sit amet amet

The way I tried it to solve myself was like this: 我尝试解决自己的方式是这样的:

new RegExp(begin_marker + "[^" + end_marker + "]*\ " + end_marker);

But this does not seem to work, and Im not sure why. 但这似乎不起作用,我不确定为什么。

You can use this kind of construct: 您可以使用这种构造:

ipsum(?:(?!ipsum).)*?amet

(?:(?!ipsum).)*? checks if each position after ipsum and before amet isn't the start of an other ipsum . 检查ipsum之后和amet之前的每个位置是否不是另一个ipsum的开始。

With the non-greedy quantifier *? 使用非贪婪量词*? , the match stop at the first amet occurrence. ,比赛会在第一次出现amet停止。


Note that the previous technique needs to perform a test with a lookahead for each position. 请注意,先前的技术需要针对每个位置提前进行测试。 If you deal with a long string, you can also play with character classes to be more efficient: 如果处理长字符串,则还可以使用字符类来提高效率:

ipsum[^ia]*(?:i(?!psum)[^ia]*|a(?!met)[^ia]*)*amet

However it's less easy to build this pattern dynamically. 但是,动态构建此模式不太容易。


When the markers are words (ie that start and end with word characters), you can limit the number of positions tested with the lookahead like this: 当标记是单词(即以单词字符开头和结尾)时,您可以像这样限制前瞻测试的位置数量:

\bipsum\W+(?:(?!ipsum\b)\w+\W+)*?amet\b

The lookahead is only tested at the start of words. 前瞻仅在单词的开头进行测试。 This one can be easily build dynamically. 这个可以很容易地动态构建。

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

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