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

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

我的奶牛总是产奶

将返回

“总是”

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

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

然而,这将返回字符串“cow 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]);
}

其他回答

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

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

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

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

cow(.*)milk

根本不需要观察头。

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

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

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

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

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

My cow always gives 
milk

正则表达式101的例子

方法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]