Reputation:
I want to extract numbers from 1 to 19 from the given string.
String n="1 21 16 17 9 8 22 20 10";
Pattern p=Pattern.compile("(1[0-9]|[0-9])");
Matcher m=p.matcher(n);
while(m.find())
System.out.println(n.substring(m.start(),m.end()));
}
Output I obtain:
1
2
1
16
17
9
8
2
2
2
0
10
Expected output should ignore 20
, 21
, 22
from the string. Right now, instead of that, 22
gets split into 2
and 2
in the display which is not expected.
Upvotes: 0
Views: 633
Reputation: 784998
Use word boundaries:
Pattern p=Pattern.compile("\\b(1[0-9]|[0-9])\\b");
Upvotes: 6
Reputation: 626738
Add word boundaries:
String n="1 21 16 17 9 8 22 20 10";
Pattern p=Pattern.compile("\\b(1[0-9]|[0-9])\\b");
Matcher m=p.matcher(n);
while(m.find())
System.out.println(n.substring(m.start(),m.end()));
}
See demo
Upvotes: 6