【问题标题】:Every string between given strings给定字符串之间的每个字符串
【发布时间】:2014-12-29 22:38:23
【问题描述】:

我需要一个位于两个字符串之间的字符串数组,但是当我使用 str.match 时,结果不是我所期望的:

var text = "first second1 third\nfirst second2 third\nfirst second3 third";
var middles = text.match(/first (.*?) third/g);
console.log(middles);  //this should be ["second1", "second2", "second3"]

结果:

["first second1 third", "first second2 third", "first second3 third"]

有什么我可以尝试只获取每次出现的中间字符串吗?

【问题讨论】:

  • 如果 Javascript 支持lookbehind,这会容易得多。然后你可以做/(?<=first ).*?(?= third)/g
  • /(?=first )(.*)( ?=third)/g 这行得通,但仍然包括 first

标签: javascript regex string substring match


【解决方案1】:

来自RegExp.prototype.exec() 的文档:

如果你的正则表达式使用“g”标志,你可以使用 exec 方法多次查找同一字符串中的连续匹配项。 当你这样做时,搜索从 str 指定的子字符串开始 正则表达式的 lastIndex 属性(test() 也会提前 lastIndex 属性)。

将此应用于您的案例:

var text = "first second1 third\nfirst second2 third\nfirst second3 third";
var middles = [], md, regex = /first (.*?) third/g;

while( md = regex.exec(text) ) { middles.push(md[1]); }

middles // ["second1", "second2", "second3"]

【讨论】:

    猜你喜欢
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 2016-12-19
    • 1970-01-01
    • 2015-05-10
    相关资源
    最近更新 更多