regex 检查给定字符串是否在单词周围有符号[关闭]

odopli94  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(90)

已关闭。此问题需要details or clarity。它目前不接受回答。
**希望改进此问题?**通过editing this post添加详细信息并阐明问题。

3天前关闭。
截至3天前,社区正在审查是否重新讨论此问题。
Improve this question
我想检查给定的字符串hasSignsAroundWords是否有这些符号:const signs = ['^', '|', '$', '#', '~', '@']; around一个单词或短语的两边,所以我现在有这个代码,它工作得很好:

console.log(1, hasSignsAroundWords('this is simple right')); // should be false

console.log(2, hasSignsAroundWords('this is ^simple right')); // should be false

console.log(3, hasSignsAroundWords('this is ^simple right^')); // should be true

console.log(4, hasSignsAroundWords('this is ^simple^ right')); // should be true

console.log(5, hasSignsAroundWords('this is ^simple^ right ^?^')); // should be true

function hasSignsAroundWords(string) {
  const signs = ['^', '|', '$', '#', '~', '@'];
  for (let a = 0; a < signs.length; a++) {
    const countSign = string.split(signs[a]).length - 1;
    if (countSign > 1 && countSign % 2 == 0) return true;
  }
  return false;
}

字符串
问题是我不想要任何英文标记像?,!:etc来遵循这个规则,所以我希望下面的日志为false,但是我的函数没有检查这个,对吗?

console.log(1, hasSignsAroundWords('this is simple right ^?^')); // should be false

console.log(2, hasSignsAroundWords('this is simple right ^!^')); // should be false

console.log(3, hasSignsAroundWords('this is simple ^,^ right')); // should be false


function hasSignsAroundWords(string) {
  const signs = ['^', '|', '$', '#', '~', '@'];
  for (let a = 0; a < signs.length; a++) {
    const countSign = string.split(signs[a]).length - 1;
    if (countSign > 1 && countSign % 2 == 0) return true;
  }
  return false;
}


你会怎么做

zqry0prt

zqry0prt1#

动态构建正则表达式,并使用反向引用来引用与结束符号相同的字符:

console.log(0, hasSignsAroundWords('this is^simple^ right')); // should be false

console.log(1, hasSignsAroundWords('this is simple right')); // should be false

console.log(2, hasSignsAroundWords('this is ^simple right')); // should be false

console.log(3, hasSignsAroundWords('this is ^simple right^')); // should be true

console.log(4, hasSignsAroundWords('this is ^simple^ right')); // should be true

console.log(5, hasSignsAroundWords('this is ^simple^ right ^?^')); // should be true

console.log(6, hasSignsAroundWords('this is simple right ^?^')); // should be false not true

console.log(7, hasSignsAroundWords('تو یه ^معامله ی^ عادلانه می خوای تو توی سیاره ی اشتباهی هستی'));

function hasSignsAroundWords(string) {
  return /(?:^|\s)([|$#~@^])[\p{L}\p{N}\s]+\1(?:$|\s)/u.test(string);
}

字符串

相关问题