【问题标题】:Get multiple substrings between " or '获取 " 或 ' 之间的多个子字符串
【发布时间】:2021-03-16 21:59:54
【问题描述】:

我试图弄清楚当子字符串位于'(单引号)或“(双引号)之间时如何获取子字符串

例子:

输入:“快”棕色“狐狸”“跳过”“懒狗”

输出:['quick', 'fox', 'jumps', 'lazy dog']

我曾尝试使用正则表达式执行此操作,但失败了。

const string = "The "quick" brown "fox" 'jumps' over the 'lazy dog'"     
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/;
console.log(strippedText.match(pattern));

但它只返回第一个单引号或双引号单词。

【问题讨论】:

  • 在模式中最后一个/ 之后使用全局标志g,并将函数从match 更改为matchAll。所以:pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;。这将返回一个数组数组,因此您需要对其进行处理以获得所需的普通数组。
  • @Samathingamajig 谢谢,我知道我忽略了一些简单的事情。
  • @Samathingamajig 请将其放入答案中,Ardz 请接受。这将帮助其他人找到答案。
  • @Tom 好的,我已经发布了答案并展示了修复嵌套数组和删除额外引号所需的额外处理

标签: javascript


【解决方案1】:

在模式中最后一个/ 之后使用全局标志g,并将函数从match 更改为matchAll。所以:pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;。这将返回一个数组数组,因此您需要对其进行处理以获得所需的普通数组。

const string = `The "quick" brown "fox" 'jumps' over the 'lazy dog'`; // Uses backticks since we use " and '
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g; // Pattern has the global flag "g" at the end so it allows multiple matches
const matches = [...string.matchAll(pattern)] // Convert RegExpStringIterator into array with the spread operator "..."
  .map(([_, first, second]) => first ?? second); // Convert the array of arrays into something sensible.
console.log(matches);

如果没有映射,匹配将如下所示:

[
    [
        "\"quick\"",
        null,
        "quick"
    ],
    [
        "\"fox\"",
        null,
        "fox"
    ],
    [
        "'jumps'",
        "jumps",
        null
    ],
    [
        "'lazy dog'",
        "lazy dog",
        null
    ]
]

所以用这一行:

.map(([_, first, second]) => first ?? second)

我们解构内部数组,丢弃第 0 个索引(这是整个匹配项,包括“不匹配”组 (?:) 中的内容,因此它包括开头和结尾的引号),并提取第一个和第二个指数。 first ?? second 表示如果first 不是nullundefined,则返回first,否则返回second

【讨论】:

    猜你喜欢
    • 2017-10-25
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 2014-04-02
    相关资源
    最近更新 更多