使用JavaScript获取两个字符串之间的字符串

37

如何使用带变量的match获取两个字符串之间的字符串?如果我使用带字符串的match,则以下代码效果很好Regular Expression to get a string between two strings in Javascript。我还尝试应用JavaScript - Use variable in string match中的信息:

var test = "My cow always gives milk";

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

但是如果我有以下情况怎么办:

var firstvariable = "cow";
var secondvariable = "milk";

var test = "My cow always gives milk";

我尝试了各种方法,包括:

var testRE = test.match("firstvariable(.*)secondvariable");
alert(testRE[1]);

并且:

var testRE = testRE.match + '("' + firstvariable + "(.*)" + secondvariable +'")';
alert(testRE[1]);

都没起作用。


1
它应该如何处理像“我的奶牛产奶。我喜欢牛奶”这样的情况?匹配应该是非贪婪的:“奶牛产奶”,还是贪婪的:“奶牛产奶。我喜欢牛奶”? - RobG
如果你要点踩,至少给一个理由。 - user3080392
2个回答

56

试试这个:

test.match(new RegExp(firstvariable + "(.*)" + secondvariable));

10
返回两个参数,第一个是完整字符串。 - Pini Cheyni
结果是一个 Array(如果没有匹配则为 null)。根据 RegExp 和测试文本,可能会有多个匹配项。结果包含 1.) 所有匹配结果 和 2.) 每个匹配组(括号中与正则表达式匹配的部分)。 例如:"xxxxABCDEFxxxxx".match(new RegExp( "AB(CD)(EF)" )) 返回 ["ABCDEF","CD","EF"]。 - Fenix
1
注意2:这是一个贪婪匹配(其结果是最长匹配字符串)。例如:"xxxxAAmCCmCCmCCxxxx".match(new RegExp( "AA(.*)CC" )) 返回 ["AAmCCmCCmCC","mCCmCCm"]。 - Fenix
如果字符串中间包含 '\n',它会如何工作? - 151291
为了使其非贪婪匹配第一个实例,将“(.?)”替换“(.)”,因此完整的内容应该是: test.match(new RegExp(firstvariable + "(.*?)" + secondvariable)); - tay

13

使用此代码

var regExString = new RegExp("(?:"+firstvariable+")((.[\\s\\S]*))(?:"+secondvariable+")", "ig"); //set ig flag for global search and case insensitive

var testRE = regExString.exec("My cow always gives milk.");
if (testRE && testRE.length > 1) //RegEx has found something and has more than one entry.
{  
    alert(testRE[1]); //is the matched group if found
}

这只匹配句子的中间部分。

  1. (?:"+firstvariable+") 查找但不捕获 cow
  2. (.*?) 捕获 cowmilk 之间的所有字符,并将其保存在一个组中。 ? 使其变为非贪婪模式,因此它会在遇到 milk 后停止。
  3. (?:"+secondvariable+") 查找但不捕获 milk

You can test this below:

function testString()
{
    var test = document.getElementById("testStringDiv").textContent;
    var firstvariable = document.querySelectorAll("input")[0].value; //first input;
    var secondvariable = document.querySelectorAll("input")[1].value; //second input;
    var regExString = new RegExp("(?:"+firstvariable+")((.[\\s\\S]*))(?:"+secondvariable+")", "ig");
    var testRE = regExString.exec(test);

    if (testRE && testRE.length > 1)
    {  
      document.getElementById("showcase").textContent = testRE[1]; //return second result.
    }
}
document.getElementById("test").addEventListener("click", testString, true);
<div id="testStringDiv">My cow always gives milk.</div>
<div id="showcase">Result will display here...</div>
<input placeholder="enter first var"/><input placeholder="enter second var"/><button id="test">Search in between...</button>


如果基础字符串中有任何换行符,则无法正常工作。 有什么解决办法吗? - Alejandro Cotilla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接