【问题标题】:How to split a string without spaces into an array of words?如何将没有空格的字符串拆分为单词数组?
【发布时间】:2019-01-30 10:01:02
【问题描述】:

所以我在 freecodecamp.org 上通过制作电话检查器的算法来练习 javascript。当只有提供的电话号码是一串数字时,我成功检查了它。现在我被卡住了,不知道如何检查提供的电话号码是否包含诸如“sixnineone”之类的词。所以我想将其拆分为“六九一”或将它们转换为带有数字对象数组的“691”。

问题出在这里:

(https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator)

我试图通过网站获得一些提示,但他们只解决了我不太了解的正则表达式的问题。

这是我所做的:

    function telephoneCheck(str) {
    let phoneNum = str.toLowerCase().replace(/[^1-9a-z]/g, "");
    let numbers = [
        {0: "o"},
        {1: "one"},
        {2: "two"},
        {3: "tree"},
        {4: "four"},
        {5: "five"},
        {6: "six"},
        {7: "seven"},
        {8: "eight"},
        {9: "nine"}
    ];

    if (phoneNum.match(/[1-9]/)) {
        phoneNum = phoneNum.split('')

        if (phoneNum.length === 10) {
            phoneNum.unshift(1);
        }

        for (let i = 0; i < phoneNum.length; i++) {
            phoneNum[i] = Number(phoneNum[i]);
        }

        if (phoneNum.length === 11 && phoneNum[0] === 1) {
            return true;
        } else {
            return false;
        }

    }

    if (phoneNum.match(/[a-z]/)) {
        console.log(phoneNum);
    }
}

console.log(telephoneCheck("sixone"));

在问题的解决方案中,据说唯一的解决方案是他们的解决方案,但如果我认为是正确的,那么可能还有另一个解决方案。

【问题讨论】:

  • 当然,通常有多种方法可以解决这样的问题。这里有一个实际的问题,还是……?
  • 我的问题是,如果数组包含单词和数字中的数字,我不知道如何拆分:“one7eightsix9tree”。我想拆分它以转换“一”、“八”、“六”、“树”,这要归功于数字数组的对象。

标签: javascript regex


【解决方案1】:

一种方法可能是使用Map 并将名称用作键,将值用作数字。

然后从映射中提取键,对它们进行排序,使最长的字符串排在第一位,并创建一个带有捕获组和alternation的正则表达式

正则表达式最终看起来像:

(three|seven|eight|four|five|nine|one|two|six|o)

然后使用这个正则表达式拆分字符串。当映射不包含键时,映射删除所有非数字的项目并从数组中删除所有空值。

最后通过key从map中获取值。

let map = new Map([
  ["o", 0],
  ["one", 1],
  ["two", 2],
  ["three", 3],
  ["four", 4],
  ["five", 5],
  ["six", 6],
  ["seven", 7],
  ["eight", 8],
  ["nine", 9]
]);
let regex = new RegExp("(" + [...map.keys()]
  .sort((a, b) => b.length - a.length)
  .join('|') + ")");

let strings = [
  "69ooooneotwonine",
  "o",
  "testninetest",
  "10001",
  "7xxxxxxx6fivetimesfifefofourt",
  "test"

].map(s =>
  s.split(regex)
  .map(x => !map.has(x) ? x.replace(/\D+/, '') : x)
  .filter(Boolean)
  .map(x => map.has(x) ? map.get(x) : x)
  .join(''));

console.log(strings);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多