3 回答
TA贡献1810条经验 获得超5个赞
正则表达式以获取Javascript中两个字符串之间的字符串
.
[^]
[\s\S]
/[\d\D]
/[\w\W]
ECMAScript 2018和新的兼容解决方案
s
.
var result = s.match(/(?<=cow\s+).*?(?=\s+milk)/gs); // Returns multiple matches if any// Orvar result = s.match(/(?<=cow\s*). *?(?=\s*milk)/gs); // Same but whitespaces are optional
cow
cow
milk
场景1:单行输入
所有JS环境都支持此方案和以下所有其他方案。参见答案底部的用法示例。
cow (.*?) milk
cow
*?
milk
场景2:多行输入
cow ([\s\S]*?) milk
cow
milk
场景3:重叠匹配
>>>15 text>>>67 text2>>>
>>>
+number
+whitespace
>>>
/>>>\d+\s(.*?)>>>/g
>>>
67
/>>>\d+\s(.*?)(?=>>>)/g
text1
text2
业绩考虑
.*?
cow
milk
"Their\ncow\ngives\nmore\nmilk"
milk
cow\n([\s\S]*?)\nmilk
/cow\n(.*(?:\n(?!milk$).*)*)\nmilk/gm
\r\n
/cow\r?\n(.*(?:\r?\n(?!milk$).*)*)\r?\nmilk/gm
JavaScript中的示例regex用法:
//Single/First match expected: use no global modifier and access match[1]
console.log("My cow always gives milk".match(/cow (.*?) milk/)[1]);
// Multiple matches: get multiple matches with a global modifier and
// trim the results if length of leading/trailing delimiters is known
var s = "My cow always gives milk, thier cow also gives milk";
console.log(s.match(/cow (.*?) milk/g).map(function(x) {return x.substr(4,x.length-9);}));
//or use RegExp#exec inside a loop to collect all the Group 1 contents
var result = [], m, rx = /cow (.*?) milk/g;
while ((m=rx.exec(s)) !== null) {
result.push(m[1]);
}
console.log(result);
添加回答
举报