【问题标题】:JS String how to extract an array of substring that matches a condition?JS String如何提取匹配条件的子字符串数组?
【发布时间】:2021-12-25 00:29:50
【问题描述】:

我有一个这样的字符串:

"|hello| + |world| / |again|"

我需要获取| 中的子字符串并返回一个这样的数组:

["hello", "world", "again"]

实现这一目标的最佳方法是什么?

【问题讨论】:

  • 可能正则表达式是一个很好的方法

标签: javascript arrays string algorithm


【解决方案1】:

array = [];
let name = "";
let input = "|hello| + |world| / |again|";
let index = 0;
let isStart = false;

while (index < input.length) {
  if (input[index] == '|') {
    isStart = !isStart;
    if (!isStart) {
      array.push(name);
      name = "";
    }
  } else {
    if (isStart) {
      name = name + input[index];
    }
  }
  index++;
}
console.log(array);

【讨论】:

  • 此解决方案允许中间有空格。例如“|一次又一次|” -> [“一次又一次”]
【解决方案2】:

您可以使用正则表达式在管道 (/|) 之间搜索仅由字母 (([A-Za-z])) 组成的组,其中管道将从实际匹配中省略(用 (?:) 包裹)- 然后使用 @ 987654321@ 获取所有匹配项,.map 仅获取捕获组的结果(省略非捕获)- 见下文:

const str = "|hello| + |world| / |again|";

const re = /(?:\|)([A-Za-z]+)(?:\|)/g;

const results = [...str.matchAll(re)].map((entry) => entry[1]);

console.log(results);

这将仅匹配管道之间的那些单词。如果您的字符串中有其他单词 not 包裹在管道之间,它们将被忽略。像下面的sn-p:

const str = "|hello| + |world| / |again| how are |you| doing?";

const re = /(?:\|)([A-Za-z]+)(?:\|)/g;

const results = [...str.matchAll(re)].map((entry) => entry[1]);

console.log(results);

【讨论】:

    【解决方案3】:

    如果该字符串不更改格式,请针对多个小写字母使用 a regular expressionmatch

    const str = '|hello| + |world| / |again|';
    const regex = /[a-z]+/g;
    console.log(str.match(regex));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-24
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2018-09-27
      相关资源
      最近更新 更多