我发现了非常相似的帖子,但我不能完全得到我的正则表达式在这里。

我试图写一个正则表达式,它返回一个字符串,这是两个其他字符串之间。例如:我想获取位于字符串“cow”和“milk”之间的字符串。

我的奶牛总是产奶

将返回

“总是”

以下是我到目前为止拼凑的表达方式:

(?=cow).*(?=milk)

然而,这将返回字符串“cow always gives”。


当前回答

我能够得到我需要使用Martinho Fernandes的解决方案如下。代码是:

var test = "My cow always gives milk";

var testRE = test.match("cow(.*)milk");
alert(testRE[1]);

您将注意到,我将testRE变量作为一个数组发出警报。这是因为由于某种原因,testRE作为数组返回。输出:

My cow always gives milk

更改为:

always gives

其他回答

可以使用match()方法在两个字符串之间提取子字符串。试试下面的代码:

var str = "My cow always gives milk";
var subStr = str.match("cow(.*)milk");
console.log(subStr[1]);

输出:

总是给

在这里查看完整的示例:如何在两个字符串之间找到子字符串。

我能够得到我需要使用Martinho Fernandes的解决方案如下。代码是:

var test = "My cow always gives milk";

var testRE = test.match("cow(.*)milk");
alert(testRE[1]);

您将注意到,我将testRE变量作为一个数组发出警报。这是因为由于某种原因,testRE作为数组返回。输出:

My cow always gives milk

更改为:

always gives

Task

在两个字符串之间提取子字符串(不包括这两个字符串)

解决方案

let allText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum";
let textBefore = "five centuries,";
let textAfter = "electronic typesetting";
var regExp = new RegExp(`(?<=${textBefore}\\s)(.+?)(?=\\s+${textAfter})`, "g");
var results = regExp.exec(allText);
if (results && results.length > 1) {
    console.log(results[0]);
}

方法match()在字符串中搜索匹配项并返回Array对象。

// Original string
var str = "My cow always gives milk";

// Using index [0] would return<br/>
// "**cow always gives milk**"
str.match(/cow(.*)milk/)**[0]**


// Using index **[1]** would return
// "**always gives**"
str.match(/cow(.*)milk/)[1]

? ?= part)不消耗任何输入。这是一个零宽度断言(边界检查和后视也是如此)。

你需要一个常规的匹配,来消耗牛的部分。为了捕获中间的部分,你使用一个捕获组(只需将你想捕获的部分放在括号内):

cow(.*)milk

根本不需要观察头。