【问题标题】:Determine if string has at least 2 same elements from an array确定字符串是否具有来自数组的至少 2 个相同元素
【发布时间】:2019-10-01 10:52:56
【问题描述】:

我想确定字符串是否至少有 2 个来自数组的相同元素

const array = ["!", "?"];

const string1 = "!hello"; // should return false
const string2 = "!hello?"; // should return false
const string3 = "!hello!"; // should return true
const string4 = "hello ??"; // should return true
const string5 = "hello ?test? foo"; // should return true
const string6 = "hello ?test ?? foo"; // should return true

我不确定哪个会更好:正则表达式还是函数?什么都可以。

我试过了:

const array = ["!", "?"];
const string = "test!";

array.every(ar => !string.includes(ar));

但它只检测数组中是否至少有 1 个元素,而不是 2 个。

【问题讨论】:

  • 数组中是否只有两个元素可以匹配,还是三个或更多?
  • 还可以更多

标签: javascript node.js regex function


【解决方案1】:

您可以使用Array#someString#split 来做到这一点:

const check=(array,string)=>array.some(char=>(string.split(char).length-1)>=2)

const array = ["!", "?"];

console.log(check(array,"!hello"))
console.log(check(array,"!hello?"))
console.log(check(array,"!hello!"))
console.log(check(array,"hello ??"))
console.log(check(array,"hello ?test? foo"))
console.log(check(array, "hello ?test ?? foo"))

它是如何工作的?

我们分手吧(我的意思是split()起来)!

const check=(array,string)=>
  array.some(char=>
    (
      string.split(char)
      .length-1
    )>=2
  )
  • 首先,使用Array#some,它测试数组的至少一个元素应该通过(即?!
  • 将字符串按char 拆分,计算我们有多少部分
    • 如果我们有n 部分,这意味着我们有n-1char 匹配的地方。 (例如 2 | 将字符串分成 3 部分:a|b|c
  • 最后,测试我们是否有 2 个或更多分隔符

【讨论】:

  • 迄今为止最好的答案,通俗易懂而且很简短!
  • 不能这样做,因为您必须等待一段时间才能接受正确答案:-)
  • 几分钟前试图接受你的问题,我认为从提出问题的那一刻起大约需要 15-20 分钟
【解决方案2】:

另一种方法是使用带有capturing group 和动态创建的character class 的模式[!?] 和反向引用\1 到组1 中捕获的内容,以确保存在2 个相同的字符.

([!?]).*\1

Regex demo

例如

const array = ["!", "?"];
const regex = new RegExp("([" + array.join(("")) + "]).*\\1");
[
  "!hello",
  "!hello?",
  "!hello!",
  "hello ??",
  "hello ?test? foo",
  "hello ?test ?? foo"
].forEach(str => console.log(str + ": " + regex.test(str)));

【讨论】:

  • 这行得通,除非数组包含元字符,例如\、]^
【解决方案3】:

您可以使用字符串split 和数组length,例如:

const array = ["!", "?"];
const string6 = "hello ?test ?? foo"; 
var len1 = string6.split(array[0]).length;
var len2 = string6.split(array[1]).length;

if (len>2)||(len2>2)
 return true;

编辑:使用 for 循环

for (let i=0;i<array.length;i++){
 var len = string6.split(array[i]).length;
 if (len>2)
  return true;
}
return false;

【讨论】:

  • 是有道理的,但如果数组包含更多元素怎么办?会有很多重复的代码
【解决方案4】:

您可以遵循如下非常简单的解决方案。使用数组中的字符拆分字符串。检查左侧的拆分操作。如果长度最小为 2,则返回 true,否则返回 false。

这是一个示例 jsFiddle:https://jsfiddle.net/sagarag05/qk8f2Lz7/

const array = ["!", "?"];
var str = "How are you!! doing !today?";

function isFound(arr, str){
  var isPresent = false;
  for(var i=0; i < arr.length; i++){
      var res = str.split(arr[i]);
      if(res.length-1 >= 2){
          isPresent = true;
          break;
      }
  }
  return isPresent;
}
isFound(array, str);

【讨论】:

  • 这行得通,但 OP 提到该数组不一定包含正好 2 个元素...
  • 没关系,这段代码只是为了给你逻辑。这可以使用 for 循环进行修改。你能分享一下你的数组中的所有字符吗?
  • 我知道怎么做,刚刚通知你,帮助你更好地回答
  • 我刚刚修改了我的代码,所以如果数组有超过 2 个元素/字符,那么它也可以工作。见上面修改后的逻辑。
【解决方案5】:

创建一个函数,方便查找n 的出现次数

const arrayData = ["!", "?"];
const strData = "test!";

function checkElements(arr, str, occNum) {
   var ctr = 0;
   arr.forEach(function (elem) { if(str.includes(elem)) ctr++});

   return ctr >= occNum
}

checkElements(arrayData, strData, 2)

【讨论】:

    【解决方案6】:

    使用循环遍历数组并计算出现次数,然后检查出现次数是否大于 1。

    function has2(string1, array)
    {
        for(let i=0;i<array.length;i++)
        {
            if (string1.split('').reduce(function(n, val) {
                    return n + (val === array[i]);
                }, 0) > 1) 
            {
                    return true;
            }
        }
        return false;
    }
    
    console.log(has2("!hello!", ["!", "?"])); // true
    console.log(has2("!hello?", ["!", "?"])); // false

    【讨论】:

      【解决方案7】:

      这是一个正则表达式技巧方法。我们可以尝试从输入中删除所有属于要查找的字符类的字符。然后,断言输入中至少有两个不同的字符。

      var input = "!hello?";
      input = input.replace(/[^!?]+/g, "");
      if (/(.).*(?!\1)./.test(input)) {
          console.log("MATCH");
      }
      else {
          console.log("NO MATCH");
      }

      这里的逻辑相当简单。以输入!hello? 为例,我们首先删除所有非标记字符,留下!?。然后,我们使用正则表达式断言至少有 两个 不同的字符剩余。这个输入确实如此,所以我们打印MATCH

      编辑:

      要从您的输入数组构建正则表达式交替,请使用join

      const array = ["!", "?"];
      var regex = "[^" + array.join("") + "]+";
      

      【讨论】:

      • 是的,蒂姆的回答不正确,应该匹配“!你好?”。
      • @Thefourthbird 我对正则表达式很陌生,我有一个问题,我可以在正则表达式字符串中使用定义的数组吗?
      • @Pleklo 我进行了更新,向您展示了如何从输入数组获取正则表达式模式。
      【解决方案8】:

      有一个更简单的解决方案:

      var a = ["!", "?"], s = "!hello!";
      a.some(v=>s.split(v).length>2) // (returns true if multiples are found)
      

      我们可以把它变成一个函数来测试:

      const a = ["!", "?"];
      function Test(s) { return a.some(v => s.split(v).length > 2) }
      const string1 = "!hello"; // should return false
      const string2 = "!hello?"; // should return false
      const string3 = "!hello!"; // should return true
      const string4 = "hello ??"; // should return true
      const string5 = "hello ?test? foo"; // should return true
      const string6 = "hello ?test ?? foo"; // should return true
      
      console.log(Test(string1), Test(string2), Test(string3), Test(string4), 
        Test(string5), Test(string6));
      
      > false false true true true true
      

      注意:我的代码更改了几次,最终接近接受的答案,但我没有意识到。也就是说,你不需要减去任何东西,所以这部分是不必要的。

      【讨论】:

        【解决方案9】:

        function checkDups(arr, str) {
            var ctr = [];
        
        
            for (var i = 0; i < arr.length; i++) {
                var pos = str.indexOf(arr[i]);
                var count = 0;
                ctr[i] = 0;
        
        
                while (pos > -1) {
                    ++count;
                    pos = str.indexOf(arr[i], ++pos);
                }
        
        
        
                if (count >= 2) {
                    return true
                }
        
            }
        
        
            return false
        }
        
        console.log(checkDups(["!", "?"], "!hello"))
        console.log(checkDups(["!", "?"], "!hello?"))
        console.log(checkDups(["!", "?"], "!hello!"))
        console.log(checkDups(["!", "?"], "hello ??"))
        console.log(checkDups(["!", "?"], "hello ?test? foo"))
        console.log(checkDups(["!", "?"], "hello ?test ?? foo"))

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-05-02
          • 2023-04-05
          • 1970-01-01
          • 2017-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多