c# - C# 正则表达式将捕获多组字符之间的选择
问题描述
我希望能够捕获##
. 例如字符串:
##First## the dog ate, ##second## the dog ran
=>['First', 'second']
The dog ##ran##
=>['ran']
##The## dog ran away from ##home##
=>['The', 'home']
我试过(?<=##).+?(?=#)
了,但它捕获了第一个字符串。
我正在使用 C#
解决方案
由于向后看和向前看,您将捕捉到中间first
和中间second
的字符串##First## the dog ate, ##second## the dog ran
要纠正这个问题,您需要使用它们:
(?:##)(?<text>.+?)(?:##)
然后当你匹配时,你可以使用组text
来提取你想要的部分。
例如:
var str = "##First## the dog ate, ##second## the dog ran";
var reg = new Regex("(?:##)(?<text>.+?)(?:##)");
var result = reg.Matches(str).Cast<Match>().Select(m => m.Groups["text"].Value);
result
将包含First
和second
推荐阅读
- video-streaming - SPICE 服务器在视频流检测中使用什么算法?
- javascript - 使用 react-native-offline 手动拦截 react-native 中的调度
- angular-material - 给出 HEX 颜色代码时如何生成颜色数组作为材料颜色生成器
- android - 如何使用以 TypeScript for Firebase Realtime 数据库编写的云函数从 onCreate 触发之外的节点获取数据?
- go - Golang 中的 bufio.NewReader(os.Stdin) 和 fmt.Scanln() 有什么区别
- graphql - 为 GraphQL 中的所有查询添加架构指令
- exception - 获取 org.xmlpull.v1.XmlPullParserException 错误:未终止的实体引用(位置:TEXT @1:683533 in java.io.InputStreamReader@a4cc4c8)
- webpack - 如何使用 dev-server watch 修复错误?
- android - 应用程序在后台时的 Firebase 控制台消息传递
- language-agnostic - 如何使代码与不同的库版本兼容,以便能够在不同的环境中运行?