js regex从文本开始获取字符串,以“start”结尾,只有“end”结束一次

时间:2012-05-12 12:45:28

标签: javascript regex

您好,

我有文字,我需要在其中找到以“start”开头并以“end”结尾的字符串。只有第一次出现。 如果字符串是:

 "just test ... bla ...bla start some txt .... end more text "
"just test ... bla ...bla start some txt .... end more text ".match(/start(.*)end/)

我得到正确的答案,数组有2个项目:

 array[0]="start some txt .... end"
 array[1]=" some txt .... "

这是完美的。 当文本包含更多的“结束”时:

"just test ... bla ...bla start some txt .... end more text  xxxx end blue fff  ...end"

我无法得到正确的字符串发生的是.match(/start(.*)end/)将所有字​​符串从第一个“开始”返回到最后一个“结束”而不是第一个“结束”: 返回:"start some txt .... end more text xxxx end blue fff ...end" 我需要的只是第一次出现:

"start some txt .... end"

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

/start(.*?)end/

?使其“非贪婪”意味着它会尽可能少地匹配

答案 1 :(得分:1)

尝试非贪婪匹配:

/start(.*?)end/