C# 正则表达式 - 只有在子字符串存在时才匹配? [英] C# Regex - only match if substring exists?

查看:39
本文介绍了C# 正则表达式 - 只有在子字符串存在时才匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Ok, so I think I've got a handle on negation - now what about only selecting a match that has a specified substring within it?

给定:

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

并尝试以下正则表达式:

And attempting the following regex:

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

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

Why isn't this working? What am I missing?

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

I'm using regexstorm.com for testing...

推荐答案

你把消极的前瞻变成了积极的前瞻,这毁了一个温和的贪婪令牌.它不会这样工作,因为正向前瞻要求文本在 This is a random bit 之后的每个位置都等于 This is a random.

You ruined a tempered greedy token by turning the negative lookahead into a positive one. It won't work that way because the positive lookahead requires the text to equal This is a random at each position after This is a random bit.

您需要:

  • 匹配前导分隔符(这是一个随机位)
  • 匹配所有 0+ 不是前导/结束定界符的文本,也不是该块内所需的随机文本
  • 匹配里面的特定字符串(This is a random)
  • 匹配所有 0+ 不是前导/结束定界符的文本
  • 匹配结束分隔符(这是结束)

所以,使用

(?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|This is the end).)* - 另一个缓和的贪婪令牌匹配任何不前导/结束分隔符直到第一个的文本......
  • 到此结束 - 尾随分隔符
  • (?s) - DOTALL mode on (. matches a newline)
  • This is a random bit - Leading delimiter
  • (?: # 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 - specified substring
  • (?:(?!This is a random bit|This is the end).)* - Another tempered greedy token matching any text not leading/closing delimiters up to the first...
  • This is the end - trailing delimiter

这篇关于C# 正则表达式 - 只有在子字符串存在时才匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆