java - Apply regex on captured group -


i'm new java , regex in particular have csv file :

col1,col2,clo3,col4 word1,date1,date2,port1,port2,....some amount of port word2,date3,date4, .... 

what iterate on each line (i suppose i'll simple loop) , ports back. guess need fetch every thing after 2 dates , ,(\d+),? , group comes back

my question(s) :

1) can done 1 expression? (meaning, without storing result in string , apply regex)

2) can maybe incorporate iteration on lines regex?

yes, can done in 1 line:

  • first remove non-port terms (those containing non-digit)
  • then split result of step 1 on commas

here's magic line:

string[] ports = line.replaceall("(^|(?<=,))[^,]*[^,\\d][^,]*(,|$)", "").split(","); 

the regex says "any term has non-digit" "term" series of characters between start-of-input/comma , comma/end-of-input.

conveniently, split() method doesn't return trailing blank terms, no need worry trailing commas left after first replace.

in java 8, can in 1 line, things more straightforward:

list<string> ports = arrays.stream(line.split(",")).filter(s -> s.matches("\\d+")).collect(collectors.tolist()); 

this streams result of split on commas, filters out non-all-numeric elements, them collects result.


some test code:

string line = "foo,12-12-12,11111,2222,bar,3333"; string[] ports = line.replaceall("(^|(?<=,))[^,]*[^,\\d][^,]*(,|$)", "").split(","); system.out.println(arrays.tostring(ports)); 

output:

[11111, 2222, 3333] 

same output in java 8 for:

string line = "foo,12-12-12,11111,2222,bar,3333,baz"; list<string> ports = arrays.stream(line.split(",")).filter(s -> s.matches("\\d+")).collect(collectors.tolist()); 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -