0

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

2
  • Where is hier coming from? Also, as written, your code will simply output an error when there are characters it does not like.. Commented May 15, 2014 at 8:30
  • Is that regex supposed to match a + 5 v 5 + 6 + 7? Commented May 15, 2014 at 8:32

2 Answers 2

2
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 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.