繁体   English   中英

C# 正则表达式 - 只有在子字符串存在时才匹配?

[英]C# Regex - only match if substring exists?

好的,所以我想我已经掌握了否定的方法 - 现在只选择一个包含指定子字符串的匹配怎么办?

鉴于:

This is a random bit of information from 0 to 1.
  This is a non-random bit of information I do NOT want to match
This is the end of this bit

This is a random bit of information from 0 to 1.
  This is a random bit of information I do want to match
This is the end of this bit

并尝试以下正则表达式:

/(?s)This is a random bit(?:(?=This is a random).)*?This is the end/g

为什么这不起作用? 我错过了什么?

我正在使用 regexstorm.com 进行测试...

你把消极的前瞻变成了积极的前瞻,这毁了一个温和的贪婪令牌。 它不会那样工作,因为正向前瞻要求文本等于This is a random at each position after This is a random bit

你需要:

  • 匹配前导分隔符( This is a random bit
  • 匹配所有 0+ 不是前导/结束定界符的文本,也不是此块内所需的随机文本
  • 匹配里面的特定字符串( This is a random
  • 匹配所有 0+ 不是前导/结束定界符的文本
  • 匹配结束分隔符( This is the end

所以,使用

(?s)This is a random bit(?:(?!This is a random bit|This is the end|This is a random).)*This is a random(?:(?!This is a random bit|This is the end).)*This is the end

查看正则表达式演示

  • (?s) - DOTALL 模式 ( .匹配换行符)
  • This is a random bit - 前导分隔符
  • (?: # Start of the tempered greedy token (?!This is a random bit # Leading delimiter | This is the end # Trailing delimiter | This is a random) # Sepcific string inside . # Any character )* # End of tempered greedy token
  • This is a random指定的子串
  • (?:(?!This is a random bit|This is the end).)* - 另一个缓和的贪婪标记匹配任何文本,直到第一个前/结束分隔符...
  • This is the end尾随定界符

我希望你明白这一点(?:(?=This is a random).)只能匹配一次,如果被量化则永远不会匹配两次。 例如Th可以满足前瞻。 T被消耗时,下一个字符是h ,它永远不会满足 Lookahhead Th 评估下一个表达式,永远不会再次返回前瞻。 改用负前瞻。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM