this question has answer here:
- regex match multiple times in string 3 answers
i'm working on c# project , need parse , extract dates strings. theese strings:
dalle ore 19.30 del 04.02.2016 alle ore 19.30 del 06.02.2016
dalle ore 19.30 del 06.02.2016 alle ore 19.30 del 08.02.2016
...
for each 1 i'd extract 2 dates (ex. 04.02.2016 06.02.2016) , save 2 variables. next i'll parse them create 2 datetime objects. i'm using code:
public static string isdate(string input) { regex rgx = new regex(@"\d{2}.\d{2}.\d{4}"); match mat = rgx.match(input); if(mat.success) return mat.tostring(); else return null; }
with code can extract first date not second one. how can improve regular expression? thanks!
try code below
static void main(string[] args) { string[] inputs = { "dalle ore 19.30 del 04.02.2016 alle ore 19.30 del 06.02.2016", "dalle ore 19.30 del 06.02.2016 alle ore 19.30 del 08.02.2016" }; string pattern = @"(?'hour'\d\d).(?'minute'\d\d)\sdel\s(?'day'\d\d.\d\d.\d\d\d\d)"; foreach (string input in inputs) { matchcollection matches = regex.matches(input, pattern); foreach (match match in matches) { timespan time = new timespan(int.parse(match.groups["hour"].value), int.parse(match.groups["minute"].value), 0); datetime date = datetime.parseexact(match.groups["day"].value, "mm.dd.yyyy", cultureinfo.invariantculture); console.writeline("time : {0}", date.add(time)); } } console.readline(); }
ok solution jdwend problem between hh.mm , date several spaces , characters. several times in form: hh:mm del dd.mm.yyyy in form dd.mm.yyyy del dd.mm.yyyy . think still possible parse data 1 regexp or have tokenize string? thank u much!
your regular expression fine, retrieve first match. matches, use matches
instead of match
:
private static final regex dateregex = new regex(@"\d{2}.\d{2}.\d{4}"); public static ienumerable<string> extractdates(string input) { return m in dateregex.matches(input).cast<match>() select m.value.tostring(); }
notes:
since regex objects thread-safe , immutable, don't need rebuild every time. can store safely in static variable.
since
matches
method predates .net generics, needcast<match>
call cast resulting collectionienumerable<match>
, can use linq.
Comments
Post a Comment