Reputation: 443
I'm emplementing a card reader and I need to use regex in android. Following wikipedia the regex for track1 is:
^%([A-Z])([0-9]{1,19})\^([^\^]{2,26})\^([0-9]{4}|\^)([0-9]{3}|\^)([^\?]+)\?$
Tried here: http://www.regexplanet.com/advanced/java/index.html with the following example: %B6011898748579348^DOE/ JOHN ^37829821000123456789? and it worked but not in my aplication.
String re = "%([A-Z])([0-9]{1,19})\\^([^\\^]{2,26})\\^([0-9]{4}|\\^)([0-9]{3}|\\^)([^\\?]+)\\?";
Pattern p = Pattern.compile(re);
String teste = "%B6011898748579348^DOE/ JOHN ^37829821000123456789?";
Matcher m = p.matcher(teste);
Log.d(TAG,"1111: "+m.groupCount());
int i=0;
for(i=0;i<m.groupCount();i++){
try{
Log.d(TAG, "GROUP"+Integer.toString(i)+" - "+m.group(i));
}catch (IllegalStateException e){
Log.d(TAG, e.toString());
}
}
Teste with ^ and $ and multiline but none worked :s the result is always:
1111: 6 java.lang.IllegalStateException: No successful match so far java.lang.IllegalStateException: No suc... ...
Upvotes: 0
Views: 133
Reputation: 124275
You need to use m.find()
first. Also you should iterate including last group. Try this way
...
if(m.find()){
Log.d(TAG,"1111: " + m.groupCount());
//change '<' into '<=' to include group 6
for(int i=0; i<=m.groupCount(); i++){
try{
Log.d(TAG, "GROUP"+Integer.toString(i)+" - "+m.group(i));
}catch (IllegalStateException e){
Log.d(TAG, e.toString());
}
}
}
Upvotes: 1