如何在 C# 正则表达式中使用后视来跳过重复前缀模式的匹配? [英] How can I use lookbehind in a C# Regex in order to skip matches of repeated prefix patterns?

查看:45
本文介绍了如何在 C# 正则表达式中使用后视来跳过重复前缀模式的匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C# 正则表达式中使用后视来跳过重复前缀模式的匹配?

How can I use lookbehind in a C# Regex in order to skip matches of repeated prefix patterns?

示例 - 我试图让表达式匹配任意数量的 a 字符之后的所有 b 字符:

Example - I'm trying to have the expression match all the b characters following any number of a characters:

Regex expression = new Regex("(?<=a).*");

foreach (Match result in expression.Matches("aaabbbb"))
  MessageBox.Show(result.Value);

返回aabbbb,lookbehind 只匹配一个a.我怎样才能使它与开头的所有 a 匹配?

returns aabbbb, the lookbehind matching only an a. How can I make it so that it would match all the as in the beginning?

我试过了

Regex expression = new Regex("(?<=a+).*");

Regex expression = new Regex("(?<=a)+.*");

没有结果...

我期待的是bbbb.

推荐答案

您是否正在寻找重复捕获组?

Are you looking for a repeated capturing group?

(.)\1*

这将返回两个匹配项.

给定:

aaabbbb

这将导致:

aaa
bbbb

这个:

(?<=(.))(?!\1).*

使用上述原则,首先检查是否找到了前一个字符,将其捕获到反向引用中,然后断言该字符不是下一个字符.

Uses the above principal, first checking that the finding the previous character, capturing it into a back reference, and then asserting that that character is not the next character.

匹配:

bbbb

这篇关于如何在 C# 正则表达式中使用后视来跳过重复前缀模式的匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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