Hello I am trying to extract a uk postcode from a string i.e. “the person’s house is at SS9 8ID we’ll be there at 8pm” so I can extract the “SS9 8ID” bit. I’ve tried the following code but it’s not working for some reason…any ideas???
String pc1="^([A-PR-UWYZ](([0-9](([0-9]|[A-HJKSTUW])?)?)|([A-HK-Y][0-9]([0-9]|[ABEHMNPRVWXY])?)) [0-9][ABD-HJLNP-UW-Z]{2})|GIR 0AA$";
String test="the person's house is at SS9 8ID we'll be there at 8pm";
Pattern pattern = Pattern.compile(pc1);
Matcher matcher = pattern.matcher(test.toUpperCase());
if (matcher.matches()) {
//Log.d("pccode:::", matcher.group(1) );
Log.d("pccode:::", matcher.group());
} else { Log.d("NO","NO PCODE"); }
The
matchesmethod matches the whole string, you should usefindinstead. And don’t use^and$in the expression.Also the
SS9 8IDdoesn’t match the regexp, becauseABD-HJLNP-UW-Zdoesn’t include letterIwhich is in the postcode.