正则表达式匹配前+删除所有文字 [英] Regex + Remove all text before match

查看:491
本文介绍了正则表达式匹配前+删除所有文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图想出一个办法,在比赛前的正则表达式去掉字符串中的所有文本。我在C#编写此。

I'm trying to figure out a way to remove all text in a string before match in Regex. I'm coding this in C#.

例如,如果字符串是你好,测试匹配,图案是测试,我想最终的结果是测试匹配(即删除测试前的所有内容)。

For example, if the string is "hello, test matching", and the pattern is "test", I would like the final result to be "test matching" (ie remove everything before test).

有什么想法? !谢谢

编辑:我也许应该已经多一点具体的在我的例子读你的反应(并感谢他们)之后。我喜欢先行的方法,但我过于简化我的例子。为了让事情变得更加困难,一般琴弦的样子:

I probably should have been a bit more specific in my example after reading your responses (and thanks for them). I like the lookahead method, but I oversimplified my example. To make things more difficult, usually the strings look like:

你好,测试匹配测试everythingAfter

"hello, test matching test everythingAfter"

所以,如果我用模式测试,它会抓住第一个。什么我的目标是,是取代第二场比赛后的所有文本。即:导致测试everythingAfter......我们对此深感抱歉。

So if I use the pattern "test", it will catch the first one. What my goal is, is to replace all text after the second match. Ie: result in "test everythingAfter".... Sorry about that.

推荐答案

*更新,使用matchcollection

*Updated, using matchcollection

string test = "hello, test matching";

string regexStrTest;
regexStrTest = @"test\s\w+";       
MatchCollection m1 = Regex.Matches(test, regexStrTest);
//gets the second matched value
string value = m1[1].Value;   

这篇关于正则表达式匹配前+删除所有文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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