c# - Would like to split a string using a regex pattern -


i have string split

var finalquote = "2012-0001-1"; var quotenum = "2012-0001"; var revision = "1" 

i used this

var quotenum = quotenum.substring(0,9); var revision = quotenum.substring(quotenum.lastindexof("-") + 1); 

but can't done using regex more efficiently? come across patterns need split two.

 var finalquote = "2012-0001-1";  string pat = @"(\d|[a-z]){4}-\d{4}";  regex r = new regex(pat, regexoptions.ignorecase);  match m = r.match(text);  var quotenum = m.value; 

so far have reached here. feel not using correct method. please guide me.

edit: wanna edit pattern. splitting dashes not option first part of split contains dash. ie, "2012-0001"

i agree others using substring better solution regex this. if you're insisting on using regex can use like:

^(\d{4}-\d{4})-(\d)$ 

untested since don't have c# environment installed:

var finalquote = "2012-0001-1"; string pat = @"^(\d{4}-\d{4})-(\d)$"; regex r = new regex(pat); match m = r.match(finalquote); var quotenum = m.groups[1].value; var revision = m.groups[2].value; 

alternatively, if want string[] try (again, untested):

string[] data = regex.split("2012-0001-1",@"-(?=\d$)"); 

data[0] quotenum , data[1] revision.


update:

explanation of regex.split:

from regex.split documentation: the regex.split methods similar string.split method, except regex.split splits string @ delimiter determined regular expression instead of set of characters.

the regex -(?=\d$) matches single - given followed a digit followed end of string match last dash in string. last digit not consumed because use zero-width lookahead assertion (?=)


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -