gpt4 book ai didi

javascript - Regex JS - 准确找到三个点

转载 作者:行者123 更新时间:2023-11-30 08:35:04 25 4
gpt4 key购买 nike

我正在尝试找出三个点,不是 4 个,不是 2 个,只有 3 个。

例如:

  • Hello world...(匹配)
  • Hello World....(不匹配)
  • .. (不匹配)
  • >。 . . (不匹配)
  • Hello World...是(匹配)
  • Hello World...[Linkebreak](匹配项)

第一个开始是:

    return text.replace(/\.{3}/g, 'FOUND!');

但效果不是很好。有什么想法吗?

最佳答案

你想要的正则表达式:

/(^|[^.])\.{3}([^.]|$)/g

你想要的 JS 替换:

text.replace(/(^|[^.])\.{3}([^.]|$)/g, '$1FOUND!$2');

这是正则表达式的分解:

  • (^|[^.]):没有字符 ^| 不是点的字符 [^. ]
  • \.{3}:后跟三个点
  • ([^.]|$) 后跟一个不是点 [^.]| 的字符字符串 $
  • $1:包含第一个捕获组
  • $2:包括最后一个捕获组

此方法的唯一缺点是将跳过由单个字符分隔的 ... 的任何组合,因此您必须运行两次替换:

... ... ... ... ...   ... => FOUND!!! ... FOUND!!! ... FOUND!!!   FOUND!!!  

测试字符串:

"This should be found -> ... \
This should not be found -> .... \
Something will be found here -> .. .. ...... ... .. \
Multiple found -> ... ... .. ... ... .. \
... <- That's found \
Next line will be found \
..."

输出 1 次迭代:

"This should be found -> FOUND!
This should not be found -> ....
Something will be found here -> .. .. ...... FOUND! ..
Multiple found -> FOUND! ... .. FOUND! ... ..
FOUND! <- That's found
Next line will be found
FOUND!"

输出 2 次迭代:

"This should be found -> FOUND!
This should not be found -> ....
Something will be found here -> .. .. ...... FOUND! ..
Multiple found -> FOUND! FOUND! .. FOUND! FOUND! ..
FOUND! <- That's found
Next line will be found
FOUND!"

关于javascript - Regex JS - 准确找到三个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32254813/

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