[英]Splitting a string with regex
I have a list of strings that look like this: 我有一个看起来像这样的字符串列表:
List<string> list = new List<string>;
list.add("AAPL7131221P00590000");
list.add("AAPL7131206C00595000");
list.add("AAPL7131213P00600000");
I would like to remove the date that is between AAPL7
and the next letter which is either C
or P
, and then add it to a new list. 我想删除AAPL7
和下一个字母C
或P
之间的日期,然后将其添加到新列表中。 How do I use regex to get: 131221
, 131206
, or 131212
so I can populate a new list? 如何使用正则表达式来获得: 131221
, 131206
,或131212
这样我就可以填充新的名单?
Consider the following code snippet... 考虑以下代码片段...
string startPattern = "AAPL7"; // GOOGL, GOOG, etc
List<string> newlist = list
.Select(n => Regex.Match(n, string.Format(@"(?<=^{0})\d+", startPattern)).Value)
.ToList();
You don't need regex for this one, you can just use Substring
, assuming that all your inputs will be the same number of characters. 您不需要正则表达式,只需使用Substring
,假设您所有的输入都将是相同数量的字符。
var startingString = "AAPL7"; // holds whatever the starting string is
var input = "AAPL7131221P00590000";
var outputDate = input.Substring(startingString.Length, 6);
So if you wanted to make this a one-liner for making a collection: 因此,如果您想使它成为收集收藏的唯一选择:
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]);
}
Is this what you want? 这是你想要的吗?
I just add something that may help in case you have the different date length (ie 14131 for 31st, January 2014) 如果您使用不同的日期长度(例如,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);
i guess it is a safe approach to handle wider cases 我想这是处理更多案件的安全方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.