java - Returning substring without markers using Pattern&Matcher -
i want use pattern , matcher return following string multiple variables.
arraylist <pattern> parray = new arraylist <pattern>(); parray.add(pattern.compile("\\[[0-9]{2}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}\\]")); parray.add(pattern.compile("\\[\\d{1,5}\\]")); parray.add(pattern.compile("\\[[a-za-z[^#0-9]]+\\]")); parray.add(pattern.compile("\\[#.+\\]")); parray.add(pattern.compile("\\[[0-9]{10}\\]")); matcher imatcher; string infostring = "[03/12/13 10:00][30][john smith][5554215445][#comment]"; (int = 0 ; < parray.size() ; i++) { //out.println(parray.get(i).tostring()); imatcher = parray.get(i).matcher(infostring); while (datematcher.find()) { string found = imatcher.group(); out.println(found.substring(1, found.length()-1)); } } }
the program outputs:
[03/12/13 10:00] [30] [john smith] [\#comment] [5554215445]
the thing need have program not print brackets , # character. can avoid printing brackets using substrings inside loop cannot avoid # character. # comment indentifier in string.
can done inside loop?
how this?
public static void main(string[] args) { string infostring = "[03/12/13 10:00][30][john smith][5554215445][#comment]"; final pattern pattern = pattern.compile("\\[#?(.+?)\\]"); final matcher matcher = pattern.matcher(infostring); while (matcher.find()) { system.out.println(matcher.group(1)); } }
you need make .+
non greedy , match between square brackets. use match group grab want rather using whole matched pattern, match group represented (pattern)
. #?
matches hash before match group doesn't group.
the match group retreived using matcher.group(1)
.
output:
03/12/13 10:00 30 john smith 5554215445 comment
Comments
Post a Comment