正则表达式执行子字符串操作 [英] Regular Expressions to perform Substring manipulation
本文介绍了正则表达式执行子字符串操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我正在尝试编写正则表达式以在c#中进行子字符串匹配.
我想将以下示例转换为正则表达式以执行完全相同的操作
字符串a = 12345678912345;
字符串b = a.Substring(4,10);
有可能吗?
谢谢
Gerom
Hi all,
I am trying to write a regular expression to do a substring match in c#.
I want to convert the example below into a regular expression to do exactly the same thing
string a = 12345678912345;
string b = a.Substring(4, 10);
Is it possible?
Thanks
Gerom
推荐答案
是的,有可能.但是,这根本不是一个好主意.
这不是正则表达式的工作,它是子字符串函数.虽然您可以创建一个正则表达式来执行此操作,但与等效的string.Substring方法相比,它的读取和维护要困难得多.
正则表达式用于模式匹配,而不是字符串提取.有时候,使用螺丝刀比使用撬棍更好.
Yes, it is possible. However, it is not a good idea at all.
That is not a job for a regular expression, it is a substring function. While you could create a regex to do it, it would be a lot harder to read and maintain than the equivalent string.Substring method.
Regular expressions are for pattern matching, not string extraction. Sometimes, it is better to use a screwdriver, than to use a crowbar...
正如格里夫已经说过的,不要这样做,以防万一您好奇您该怎么做:
As Griff already said, don''t do it, bit just in case you got curious this is how you could do it:
Regex regex = new Regex(".{4,}(?<rest>.*)");
MatchCollection matchCollection=regex.Matches("1234567890");
foreach(Match match in matchCollection)
{
Console.WriteLine("Rest: {0}", match.Groups["rest"]);
}
干杯!
Cheers!
这篇关于正则表达式执行子字符串操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文