Regex.Match和Regex.Split组合 [英] Regex.Match and Regex.Split combinations

查看:64
本文介绍了Regex.Match和Regex.Split组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

在我的应用程序中,我想将一个字符串分成两部分,我知道我们可以通过使用Regex.Split来做到这一点。但在我的情况下条件有点不一样。

看,

我的字符串是012AA23SB45AA78

如果我使用Regex.Split(012AA23SB45AA78,AA)将返回一个字符串数组,如

012

23SB45



但我需要两个字符串一个是012AA23SB45 而另一个是78。(意味着将字符串拆分成最后一个Regex.match的两个部分。是否有可能使用Regex.match和Regex.Split的组合来做到这一点.... ??



提前致谢

-Manuprasad M

解决方案

Regex.Split这不是你需要的 - 你可能更适合使用股票匹配操作和使用组,或者更好的是,只需通过LastIndexOf和子串手动操作:

  string  inp =   012AA23SB45AA78; 
int index = inp.LastIndexOf( AA);
string start = inp.Substring( 0 ,index);
string end = inp.Substring(index + 2 );


为什么不使用 string.LastIndexOf string.Substring 这样做?



尝试这样的事情:

 var firstPart = s.Substring(0,s .LastIndexOf( 'AA')); 
var lastPart = s.Substring(s.LastIndexOf('AA')+ 2);





祝你好运!


如果您需要最后一个 AA 之前的所有内容,您只需使用Regex.Match,^ (。*)AA。*

Hi all,
In my application I want to split a string into two pieces, I know we can do that by using "Regex.Split ".But in my case the condition is little bit different.
See,
My string is "012AA23SB45AA78"
if I use Regex.Split("012AA23SB45AA78","AA") will return a string array like
012
23SB45
78
but I need just two strings one is "012AA23SB45" and the other is "78".(means split the string into two pieces where the last Regex.match occurred. Is there is any possibilities to do this using the combinations of Regex.match and Regex.Split....??

Thanks in advance
-Manuprasad M

解决方案

Regex.Split isn't what you need here - you are probably better going with a "stock" Match operation and using the groups, or better still, just doing it manually via LastIndexOf and Substring:

string inp = "012AA23SB45AA78";
int index = inp.LastIndexOf("AA");
string start = inp.Substring(0, index);
string end = inp.Substring(index + 2);


Why not use a combination of string.LastIndexOf and string.Substring to do it?

Try something like this:

var firstPart = s.Substring(0, s.LastIndexOf('AA'));
var lastPart = s.Substring(s.LastIndexOf('AA') + 2);



Good luck!


If you need everything before the last AA, you can simply use Regex.Match also, with "^(.*)AA.*


这篇关于Regex.Match和Regex.Split组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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