Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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?

like image 239
Seiya Avatar asked Jun 06 '26 02:06

Seiya


1 Answers

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);
}
like image 167
Pshemo Avatar answered Jun 08 '26 16:06

Pshemo