验证一个字符串是否仅包含某个特定子串的单个出现

3

我正在尝试匹配符合以下条件的完整字符串:

  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}}))/

1个回答

2

您可以使用

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

请查看正则表达式演示

细节:

  • ^ - 字符串的开头
  • (?!(?:.*?{{REPLACE}}){2}) - 负向先行断言,如果当前位置的右侧有两个任意数量的零个或多个字符序列(除换行符之外),然后是{{REPLACE}}子字符串,则匹配失败
  • .*? - 任意数量的零个或多个字符,尽可能少地匹配
  • {{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))
)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接