1

I found this question on how to port PHP's preg_match to Java (it recommends using String.matches(). However, I still have trouble with the following situation:

PHP:

preg_match('/<(h1|h2|h3|h4|ul|td|div|table)/i', '<h1>') => returns 1

Java:

"<h1>".matches("/<(h1|h2|h3|h4|ul|td|div|table)/i") => return false

Why would that be?

3 Answers 3

1

In Java, matches() requires a full string match. And you do not need regex delimiters.

"<h1>".matches("(?i)<(h1|h2|h3|h4|ul|td|div|table)>")

See IDEONE demo

If you plan to use the same regex in Java, use Matcher with find() (find will match anywhere in the input string and Pattern.CASE_INSENSITIVE will act as i option in PHP):

String str = "<h1>";
String rx = "<(h1|h2|h3|h4|ul|td|div|table)";
Pattern ptrn = Pattern.compile(rx, Pattern.CASE_INSENSITIVE);
Matcher m = ptrn.matcher(str);
while (m.find()) {
    System.out.println(m.group(0));
}

See another demo

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

2 Comments

Is there a less horrible API than Patter.compile thing?
If you ask me for a substitution, I do not know any. I just provided this to show how you can use the same regex in Java and PHP without editing the regex itself. You can actually write a separate wrapper method to simplify invoking the replacement, but you will still have to add the import java.util.regex.*; import.
1
  • You need to remove the regex delimiters.

  • And also you need to add (?i) modifier for doing case-insensitive match.

  • Finally you have tyo add > at the last since matches method tries to match the whole string.

    "<h1>".matches("(?i)<(h1|h2|h3|h4|ul|td|div|table)>");
    

2 Comments

Sorry I realised that this is not a correct answer. While php version would match <h1>hello</h1>, java version wouldn't
then you need to use Pattern and Matcher classes.
0

In Java it should be:

"<h1>".matches("(?i)<(h[1234]|ul|td|div|table)>");

i.e. no regex delimiter and (?i) for ignore-case comparison.

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.