\" or a newline, but not includes any of them." />
开发者

Longest string A a RegExp finds from start, following but not including B

I failed formulating the RegExp finding

  • the longest and
  • not empty sequence from start, that is
  • maybe followed by a "<%" or "%>" or a newline, but not includes any of them.

I tried /^.+?(?=\r?\n|\r|<%|%>)?/, but it always only matches the first character.

E.g. e = /^.+?(?=\r?\n|\r|<%|%>)?/.exec("test\nabc") finds e[0] = "t".

Of cause, grepping for /\r开发者_如何学Python?\n|\r|<%|%>/ would be possible, but maybe one of you knows a better method.


Your pattern is pretty close. ^.+? is lazy, it matches as much as it has to. With (?=\r?\n|\r|<%|%>)? being optional, it never has to backtrack - the regex is satisfied after a single character. Removing the ? will have much better results, but it doesn't take care of a single line of text with no stop words.
A simpler approach is to use the /m flag, which makes $ match the end of the string or the end of the line:

/^.*?(?=$|<%|%>)/m

I've also changes + to * - it should take care of empty lines, or lines that begin with <% or %>.

Working example: http://rubular.com/r/l8Gmhc459i


If I understand your question correctly, this one should do the trick:

var re = /^(?:(?![\r\n]|<%|%>).)+/;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜