【问题标题】:Check occurrence of element in string with Regex?使用正则表达式检查字符串中元素的出现?
【发布时间】:2021-07-26 00:34:35
【问题描述】:

我有字符串,其中一些可能包含

:
=
我想找到所有出现这些符号的情况,但只有一次(!)。

我写了这段代码,它有效,但想用正则表达式解决

function find(stringToCheck: string): string {
    return stringToCheck.includes(':') &&
        stringToCheck.split(':').length - 1 === 1
        ? ':'
        : stringToCheck.includes('=') && stringToCheck.split('=').length - 1 === 1
        ? '='
        : '';
}

【问题讨论】:

  • 那么每个字符:= 是否允许在字符串中存在一次?或者您是说字符串中只允许存在一个字符并且它只能存在一次?
  • 或者你是说如果:只存在一次,那么=可以存在多次?反之亦然...
  • 没错,这些字符中只有一个允许存在于字符串中,并且只能存在一次。如果 : 存在,= 根本不应该存在

标签: javascript regex typescript


【解决方案1】:

搜索字符串以查找与:= 匹配的字符串,然后将其存储为RegExp match array。然后这个数组的长度与找到的字符串实例的数量相匹配。

在创建 RexExp 对象的位置,标志 "g" 用于查找所有匹配项,而不仅仅是第一个匹配项。

function find (stringToTest) {
  const a = stringToTest.match(new RegExp(":", "g"));
  const b = stringToTest.match(new RegExp("=", "g"));
  if (a?.length > 1 || b?.length > 1) return true;
  return false;
}

console.log(find("hello:world=")); // false
console.log(find("hello world")); // false
console.log(find("hello world====")); // true

【讨论】:

  • 帮了大忙,谢谢,不过我只需要出现一次就返回true,所以通过测试第三种情况,函数应该返回false
  • 已编辑以匹配您的用例 - 希望这很好。
【解决方案2】:

试试这个:

function find (stringToCheck)
{
  return (/^[^:]*:[^:]*$/.test(stringToCheck) && /^[^=]*=?[^=]*$/.test(stringToCheck))||(/^[^:]*:?[^:]*$/.test(stringToCheck) && /^[^=]*=[^=]*$/.test(stringToCheck));
}

console.log(find("iron:man"));
console.log(find("iron=man"));
console.log(find("iron::man"));
console.log(find("iron==man"));
console.log(find("ironman"));

【讨论】:

    【解决方案3】:

    你可以使用:

    ^[^:=]*[:=][^:=]*$
    

    function checkString(str){
        return /^[^:=]*[:=][^:=]*$/.test(str);
    }
    
    console.log(checkString('Neither'));
    console.log(checkString('One equal ='));
    console.log(checkString('One colon :'));
    console.log(checkString('colon equal :='));
    console.log(checkString('Multiple = equal ='));
    console.log(checkString('Multiple : colon :'));
    console.log(checkString('Multiple = both : col=on :'));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多