0

I was trying to match the example in , <p><a href="example/index.html">LinkToPage</a></p>

With rubular.com I could get something like <a href=\"(.*)?\/index.html\">.*<\/a>.

I'll be using this in Pattern.compile in Java. I know that \ has to be escaped as well, and I've come up with <a href=\\\"(.*)?\\\/index.html\\\">.*<\\\/a> and a few more variations but I'm getting it wrong. I tested on regexplanet. Can anyone help me with this?

8
  • 2
    No escaping necessary here. Just use ...=\"... A backslash only needs to be escaped, when you actually want a backslash. And in a regex, you have to do it twice. Commented Jun 3, 2013 at 19:34
  • 1
    If it's an escaping issue, try printing your string to the command line to figure out what it thinks it is and correcting accordingly. All those backslashes can get annoying. Commented Jun 3, 2013 at 19:35
  • 3
    Since this is HTML, you should consider using an HTML parser... Like, for instance, jsoup. Commented Jun 3, 2013 at 19:38
  • 1
    You don't need \ before / Commented Jun 3, 2013 at 19:38
  • 1
    replace ...\/... with .../... Commented Jun 3, 2013 at 19:38

3 Answers 3

2

Use "<a href=\"(.*)/index.html\">.*</a>" in your Java code.

You only need to escape " because it's a Java string literal.

You don't need to escape /, because you aren't delimiting your regex with slashes (as you would be in Ruby).

Also, (.*)? makes no sense. Just use (.*). * can already match "nothing", so there's no point in having the ?.

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

Comments

1
Pattern.compile("<a href=\"(.*)?/index.html\">.*</a>");

That should fix your regex. You do not need to escape the forward slashes.

However I am obligated to present you with the standard caution against parsing HTML with regex:

RegEx match open tags except XHTML self-contained tags

Comments

0

You can tell Java what to match and call Pattern.quote(str) to make it escape the correct things for you.

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.