如何捕获由特定单词分隔的字符串的不同 x 部分
How to capture distinct x portions of a string separated by a specific word
考虑到这一点:
{
author={Diaz, Navarro David and Gines, Rodriguez Noe},
year={2006},
month=jul # "~12",
note={EP Patent 1,678,025}
}
我想在作者字段中匹配并捕获由 "and" 分隔的不同名称组(在这种情况下:Diaz、Navarro David 和 Gines、Rodriguez Noe)可能出现超过 2 次
到目前为止,regex 使用正向后视可以捕获卷曲中的所有内容(如果前面有 'author={'),但我正在努力捕获满足上述条件的 2 个组。帮助! :)
(?<=author=\{)([^}]+)
要匹配整个部分,您可以重复字符 class:
如果 and
介于两者之间,您可以使用 2 个捕获组:
(?<=author={)([^}]*) and ([^}]*)
请注意,Javascript 中的所有浏览器尚未完全支持后视。
另一种选择是匹配零件而不是使用环视:
\bauthor={([^}]+) and ([^}]+)},
最好的方法是抓取 author={
和 }
之间的子字符串,然后用 and
整个单词拆分第 1 组值:
var str = '{\n author={Diaz, Navarro David and Gines, Rodriguez Noe and Another, John Doe},\n year={2006},\n month=jul # "~12",\n note={EP Patent 1,678,025}\n}';
var m = /author={([^{}]*)}/.exec(str);
if (m) {
console.log(m[1].trim().split(/\s*\band\b\s*/));
}
如果您必须使用单个正则表达式来做到这一点,您应该以支持无限宽度后视的最新 ECMAScript 标准为目标。
以下代码将在当前 Chrome 版本中工作:
var str = '{\n author={Diaz, Navarro David and Gines, Rodriguez Noe and Another, John Doe},\n year={2006},\n month=jul # "~12",\n note={EP Patent 1,678,025}\n}';
var rx = /(?<=author={[^{}]*?)(?<![^{\s])(?:(?!\band\b)[^{}])+\b(?<!\s)/g;
console.log(str.match(rx));
详情
(?<=author={[^{}]*?)
- 如果在当前位置的左侧有 author={
子字符串后跟除 [= 以外的任何 0+ 个字符,则 returns 为真17=]和}
,越少越好
(?<![^{\s])
- 此外,如果紧邻当前位置的左侧除了空格或 {
(修剪左侧的匹配)没有其他字符,则仅匹配下一个模式
(?:(?!\band\b)[^{}])+
- 除 {
和 }
以外的任何字符,出现 1 次或多次,不以整个单词开头 and
(?<!\s)
- 如果在当前位置的左侧没有空格(修剪右侧的匹配项),则 returns 为真。
考虑到这一点:
{
author={Diaz, Navarro David and Gines, Rodriguez Noe},
year={2006},
month=jul # "~12",
note={EP Patent 1,678,025}
}
我想在作者字段中匹配并捕获由 "and" 分隔的不同名称组(在这种情况下:Diaz、Navarro David 和 Gines、Rodriguez Noe)可能出现超过 2 次
到目前为止,regex 使用正向后视可以捕获卷曲中的所有内容(如果前面有 'author={'),但我正在努力捕获满足上述条件的 2 个组。帮助! :)
(?<=author=\{)([^}]+)
要匹配整个部分,您可以重复字符 class:
如果 and
介于两者之间,您可以使用 2 个捕获组:
(?<=author={)([^}]*) and ([^}]*)
请注意,Javascript 中的所有浏览器尚未完全支持后视。
另一种选择是匹配零件而不是使用环视:
\bauthor={([^}]+) and ([^}]+)},
最好的方法是抓取 author={
和 }
之间的子字符串,然后用 and
整个单词拆分第 1 组值:
var str = '{\n author={Diaz, Navarro David and Gines, Rodriguez Noe and Another, John Doe},\n year={2006},\n month=jul # "~12",\n note={EP Patent 1,678,025}\n}';
var m = /author={([^{}]*)}/.exec(str);
if (m) {
console.log(m[1].trim().split(/\s*\band\b\s*/));
}
如果您必须使用单个正则表达式来做到这一点,您应该以支持无限宽度后视的最新 ECMAScript 标准为目标。
以下代码将在当前 Chrome 版本中工作:
var str = '{\n author={Diaz, Navarro David and Gines, Rodriguez Noe and Another, John Doe},\n year={2006},\n month=jul # "~12",\n note={EP Patent 1,678,025}\n}';
var rx = /(?<=author={[^{}]*?)(?<![^{\s])(?:(?!\band\b)[^{}])+\b(?<!\s)/g;
console.log(str.match(rx));
详情
(?<=author={[^{}]*?)
- 如果在当前位置的左侧有author={
子字符串后跟除 [= 以外的任何 0+ 个字符,则 returns 为真17=]和}
,越少越好(?<![^{\s])
- 此外,如果紧邻当前位置的左侧除了空格或{
(修剪左侧的匹配)没有其他字符,则仅匹配下一个模式(?:(?!\band\b)[^{}])+
- 除{
和}
以外的任何字符,出现 1 次或多次,不以整个单词开头and
(?<!\s)
- 如果在当前位置的左侧没有空格(修剪右侧的匹配项),则 returns 为真。