[英]Splitting a string with regex
我有一个看起来像这样的字符串列表:
List<string> list = new List<string>;
list.add("AAPL7131221P00590000");
list.add("AAPL7131206C00595000");
list.add("AAPL7131213P00600000");
我想删除AAPL7
和下一个字母C
或P
之间的日期,然后将其添加到新列表中。 如何使用正则表达式来获得: 131221
, 131206
,或131212
这样我就可以填充新的名单?
考虑以下代码片段...
string startPattern = "AAPL7"; // GOOGL, GOOG, etc
List<string> newlist = list
.Select(n => Regex.Match(n, string.Format(@"(?<=^{0})\d+", startPattern)).Value)
.ToList();
您不需要正则表达式,只需使用Substring
,假设您所有的输入都将是相同数量的字符。
var startingString = "AAPL7"; // holds whatever the starting string is
var input = "AAPL7131221P00590000";
var outputDate = input.Substring(startingString.Length, 6);
因此,如果您想使它成为收集收藏的唯一选择:
List<string> allDates = yourInputValues
.Select(x => x.Substring(startingString.Length, 6))
.ToList();
//Regex regex = new Regex("(\\w{5})(\\d*)(\\w*)");
Regex regex = new Regex("(\\w*)(\\d{6})([PC])(\\d*)");
List<string> list = new List<string>();
list.Add("AAPL7131221P00590000");
list.Add("AAPL7131206C00595000");
list.Add("AAPL7131213P00600000");
List<string> extracted = new List<string>();
foreach (string item in list)
{
extracted.Add(regex.Split(item)[2]);
}
这是你想要的吗?
如果您使用不同的日期长度(例如,2014年1月31日为14131),我只是添加一些可能会有所帮助的内容
string startpart = "AAPL7"; // or whatever
string mainstring = "AAPL714231P00590000"; // or any other input
mainstring = mainstring.Substring(startpart.Length); //this will through away startpart
int index;
if (mainstring.IndexOf("P") >= 0) index = mainstring.IndexOf("P"); //if there is no "P" it gives -1
else index = mainstring.IndexOf("C");
string date = mainstring.Substring(0,index);
我想这是处理更多案件的安全方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.