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

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

我的奶牛总是产奶

将返回

“总是”

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

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

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


当前回答

如果数据在多行上,那么您可能必须使用以下方法,

/My cow ([\s\S]*)milk/gm

My cow always gives 
milk

正则表达式101的例子

其他回答

我能够得到我需要使用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

下面是一个正则表达式,它将抓取奶牛和牛奶之间的内容(没有前导/尾随空格):

srctext = "My cow always gives milk.";
var re = /(.*cow\s+)(.*)(\s+milk.*)/;
var newtext = srctext.replace(re, "$2");

示例:http://jsfiddle.net/entropo/tkP74/

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

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

输出:

总是给

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

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]);
}

只需使用下面的正则表达式:

(?<=My cow\s).*?(?=\smilk)