Java regex using pattern matcher not returning correctly? -
i have index value following string:
home.number[12].parent.
i want value of 12.
here tried:
//escape . / [ ] private static final string pattern = "home\\.number\\[([0-9]*)\\]*"; private static final pattern addresspattern = pattern.compile(pattern); private static int getindex(string input, pattern pattern){ matcher m = pattern.matcher(input); if (m.matches()){ return integer.valueof(m.group(2)); } return -1; } public static void main(string[] args){ system.out.println(getindex("home.number[123].parent", addresspattern); system.out.println(getindex("home.number[456].child", addresspattern); }
i -1
both, meaning no match found.
using debugger, found m.matches()
returning false
. unable figure out why.
p.s: tried using pattern.quote("home.number[([0-9]*])*")
, stringutils.escapejava("home.number[([0-9]*)]*")
. both not returning matching results.
your pattern
should like
private static final string pattern = "home\\.number\\[(\\d+)\\]\\..*"; private static final pattern addresspattern = pattern.compile(pattern);
and matcher has 1
group.
private static int getindex(string input, pattern pattern) { matcher m = pattern.matcher(input); if (m.matches()) { return integer.parseint(m.group(1)); } return -1; }
and need close second paren in calls in main
. like
public static void main(string[] args) { system.out.println(getindex("home.number[123].parent", addresspattern)); system.out.println(getindex("home.number[456].child", addresspattern)); }
when make changes expected
123 456
Comments
Post a Comment