Reputation: 235
I have a StringBuilder and i want to get characters except numbers and following characters(+, -, *, /).
I wrote this code.
StringBuilder sb = new StringBuilder(" a + 5 v 5 + 6 + 7");
String nieuw = trimOriginal(sb);
System.out.println(nieuw);
if(nieuw.matches("[a-zA-Z ]*\\d+.*")){
System.out.println(nieuw);
}else {
System.out.println("contains illegal charters");
}
public static String trimOriginal(StringBuilder sb) {
return sb.toString().trim();
}
i want print hier also a and v.
can somebody help me
Upvotes: 0
Views: 100
Reputation: 1921
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(" a + 5 v 5 + 6 + 7");
String nieuw = trimOriginal(sb);
System.out.println(nieuw);
if (nieuw.matches("[^0-9+/*-]+")) {
System.out.println(nieuw);
} else {
System.out.println("contains illegal charters");
}
}
public static String trimOriginal(StringBuilder sb) {
String buff = sb.toString();
String[] split = buff.split("[0-9+/*-]+");
StringBuilder b = new StringBuilder();
for (String s : split) {
b.append(s);
}
return b.toString().trim();
}
OUTPUT
a v
a v
Upvotes: 2
Reputation: 52185
The problem with matches
is that it will attempt to match the entire string. Changing it to something like so should work:
StringBuilder sb = new StringBuilder(" a + 5 v 5 + 6 + 7");
Pattern p = Pattern.compile("([^0-9 +*/-])");
Matcher m = p.matcher(sb.toString());
while(m.find())
{
System.out.println(m.group(1));
}
Yields: a v
.
Upvotes: 1