Seiya
Seiya

Reputation: 31

Java 1.7. How to replace two characters side by side in a regular expression?

I have the code:

String str = "1 */ * / 2";

str = str.replaceAll("\\*/", " ");

System.out.println(str);

He gives me the next result and it's correct:

1 * / 2

But I need to get the opposite result, and I do:

String str = "1 */ * / 2";

str = str.replaceAll("[^\\*/]", " ");

System.out.println(str);

and get:

*/ * /

But not:

*/

I need to get only these two characters together, excluding separately * and /

How can i do this?

Upvotes: 3

Views: 206

Answers (1)

Pshemo
Pshemo

Reputation: 124295

replaceAll(regex, replacement) tries to search for pattern represented by regex and replace that match with content of replacement. If you don't want to replace it, but lets say only print it, instead of String#replaceAll use Matcher#find like

String str = "1 */ * / 2";

Pattern p = Pattern.compile("\\*/");
Matcher m = p.matcher(str);
while(m.find()){
    String match = m.group();
    //do something with match
    System.out.println(match);
}

Upvotes: 1

Related Questions