首页 > 解决方案 > 通过C#中的正则表达式获取子字符串

问题描述

string string1 = @"Comments by fkhan19 on Nov 01, 2018: 'ok' Comments by mzaighum on Oct 31, 2018: 'Rs.12,000,000 available in Gas is recommended for reallocation to Gen. Fuel. "

我有上面的字符串,想在 fkhan19 的评论之间提取文本 .... mzaighum 的评论

我怎样才能通过正则表达式做到这一点。

标签: c#regex

解决方案


你可以使用

[Cc]omments by [^ ]+(.+?)(?=[Cc]omments by|$)

或者

[Cc]omments by [^ ]+(.+?)(?=[Cc]omments by)

第一个模式的演示

第二种模式的演示

第一种模式的解释(第二种非常相似):

[Cc]- 匹配cC

omments byomments by-从字面上匹配

[^ ]+- 匹配一个或多个除空格以外的任意字符

(.+?)- 匹配一个或多个任意字符(非贪心)

(?=[Cc]omments by|$)- 积极的前瞻:确保接下来是模式[Cc]omments by(如上所述)或字符串结尾$


推荐阅读