regex - Is there any efficient Java solution/Algorithm to find values in a text field based on key string with delimiter? -


is there efficient java solution/algorithm find values in text field based on key string delimiter?

example:

rules:

i. key: username start-delimiter: ; end-delimiter: ;

need find value if followed key( in case username ) , value between start , end delimiters(in case ;).

ii. key: on start-delimiter: ; end-delimiter: ;

sample input:

a user username ;suren; logged system on ;thu may 2, 2013 2:30pm;

results: i. username - suren ii. on - thu may 2, 2013 2:30pm

here example of have tried far:

string key = "username "; string startdelimiter = ";"; string enddelimiter = ";"; string computedpattern = "(\\w+)" + key + startdelimiter + "(\\w+)" + enddelimiter; pattern p = pattern.compile(computedpattern); matcher m = p.matcher(   "a user username ;suren; logged system on ;thu may 2, 2013 2:30pm;"); while( m.find() ) {   system.out.println( "key:" + m.group(1) + "value:" + m.group(2) ); } 

the problem in approach arises construction of regex. if @ java docs pattern class, see \w matches word characters: [a-za-z_0-9]

it sounds want match characters between semicolons after defined key number on spaces in between. right pattern following:

arraylist<string> keys = new arraylist<string>(); keys.add("username"); keys.add("on"); string startdelimiter = ";"; string enddelimiter = ";"; string searchstr = "a user username ;suren; logged system on ;thu may 2, 2013 2:30pm;";        (string key : keys) {     pattern p = pattern.compile("("+key+")[ ]+?"+startdelimiter+"([^;]+)"+enddelimiter);     matcher m = p.matcher(searchstr);        while( m.find() ) {         system.out.println("key: "+m.group(1)+" value: "+m.group(2));     } } 

the character class [^;]+ job you, since matches non empty character sequence characters different ";".


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

java - Using an Integer ArrayList in Android -