2

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("[ '-_()]", "");
2
  • 1
    Don't escape more than you need to. Your second pattern could just as well be [ '-_()] (although in PHP you'd still have to escape the ', of course). Commented Jun 26, 2013 at 18:42
  • If you're not using any non-core regex features, regexes are the same everywhere and the only thing to look out for is stuff like whether you need to double up (escape) backslashes or not, multi-line behaviour, etc Commented Jun 27, 2013 at 0:53

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!)) Yep! Surely I add the example of input string when I would be know it. At this time I don't know what is it)
2

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.