gpt4 book ai didi

javascript - 验证仅包含某个特定子字符串一次出现的字符串

转载 作者:行者123 更新时间:2023-12-04 15:06:17 26 4
gpt4 key购买 nike

我正在尝试匹配整个字符串:

  1. 只出现了一次指定的单词
  2. 允许出现之前和之后的任何内容,除了指定的词

理想的结果是这样的:

{{REPLACE}}. // Valid
{{REPLACE}} {{REPLACE}}. // Invalid
{{REPLACE}}{{REPLACE}}. // Invalid
Text here {{REPLACE}}. More text here. // Valid
{{REPLACE}} text here {{REPLACE}}. More text here // Invalid

我最接近的是

{{REPLACE}}. // Valid
{{REPLACE}} {{REPLACE}}. // Valid
{{REPLACE}}{{REPLACE}}. // Invalid
Text here {{REPLACE}}. More text here. // Valid
{{REPLACE}} text here {{REPLACE}}. More text here // Valid

使用 /(?<!({{REPLACE}}))({{REPLACE}}){1}(?!({{REPLACE}}))/

最佳答案

你可以使用

/^(?!(?:.*?{{REPLACE}}){2}).*?{{REPLACE}}/             // If no line breaks are present
/^(?!(?:[\w\W]*?{{REPLACE}}){2})[\w\W]*?{{REPLACE}}/ // If there can be line breaks

参见 regex demo

详细信息:

  • ^ - 字符串的开始
  • (?!(?:.*?{{REPLACE}}){2}) - 如果在当前位置的右侧紧邻有除换行符以外的任何零个或多个字符的两个序列尽可能少,然后 {{REPLACE}} substring
  • .*? - 除换行符外的任何零个或多个字符尽可能少
  • {{REPLACE}} - {{REPLACE}} 子字符串(或某些特定模式)。

如果你需要像这样匹配整行,你应该将 .* 添加到第一个模式并使用 gm 标志:

/^(?!(?:.*?{{REPLACE}}){2}).*?{{REPLACE}}.*/gm

查看 JavaScript 演示:

const texts = ['{{REPLACE}}.', '{{REPLACE}} {{REPLACE}}.', '{{REPLACE}}{{REPLACE}}.', 'Text here {{REPLACE}}. More text here.','{{REPLACE}} text here {{REPLACE}}. More text here'];
const regex = /^(?!(?:.*?{{REPLACE}}){2}).*?{{REPLACE}}/;
texts.forEach( x =>
console.log(x, '=>', regex.test(x))
)

关于javascript - 验证仅包含某个特定子字符串一次出现的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66031747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com