Kohnarik Kohnarik - 6 months ago 14
Java Question

Java get special characters from string

Given a random String, I want to be able to extract certain characters from my string (

+
,
-
,
*
,
/
), one after each other.

Let's say the String is
wejri+234-wer*324sdf/

How can I retrieve those 4 operators?

If I had to extract everything between those operators, I would use
String.split("\\+|\\-|\\*|\\/");
, but if I had to do it the other way around, how would I achieve that?

The amount of characters between those operators can vary heavily.

Answer

You can use a regex to remove all characters but +, -, *, /:

String text = "wejri+234-wer*324sdf/";
String res = text.replaceAll("[^+\\-\\*/]", "");   // - and * need to be escaped
// > res = "+-*/"