falcon
falcon

Reputation: 362

convert php regex to java regex

Can somebody help me with converting a php regex to java regex?

It would be great and I would be appreciate you if you can help me, because I'm not so strong in regex.

$str = preg_replace ( '{(.)\1+}', '$1', $str )
$str = preg_replace ( '{[ \'-_\(\)]}', '', $str )

How I understand preg_replace function in php is the same as replaceAll in java?.. So in java code it would be like this.

str = str.replaceAll("{(.)\1+}", "$1");
str = str.replaceAll("{[ \'-_\(\)]}", "");

But this code wont be work because how I know that regex in php is different by java.

Please, somebody help me! Thanks a lot))

update

final result is

str = str.replaceAll("(.)\\1+", "$1");
str = str.replaceAll("[ '-_()]", "");

Upvotes: 2

Views: 3666

Answers (2)

Achrome
Achrome

Reputation: 7821

The only difference with Java regex is that you have to escape the backslashes.

str = str.replaceAll("(.)\\1+", "replacerString");
str = str.replaceAll("[ \\'-_\\(\\)]", "");

Upvotes: 2

anubhava
anubhava

Reputation: 785256

For this PHP regex:

$str = preg_replace ( '{(.)\1+}', '$1', $str );
$str = preg_replace ( '{[ \'-_\(\)]}', '', $str )

In Java:

str = str.replaceAll("(.)\\1+", "$1");
str = str.replaceAll("[ '-_\\(\\)]", "");

I suggest you to provide your input and expected output then you will get better answers on how it can be done in PHP and/or Java.

Upvotes: 2

Related Questions