简体   繁体   中英

Regex matches but doesn't work on Java

I'm using this regex to match and replace a part of a string:

(.*)<a href=\\"(.*)\\" class=\\"PopupItemLink\\">(.*)<\\\/a>(.*)

This string is an example: ( https://regexr.com/3n1f1 )

\n&7This is the alert body\n\nYour name: HAlexTM\nYour ID: 1\nHere the link: <a href=\"test.com\" class=\"PopupItemLink\">Hey<\/a>\n\nThis is a html test: <p>Hey<\/p>\n&8Thu Jun 09 18:07:30 CEST 2016

This part of the string (matched by the RegEX) should be replaced with Hey

<a href=\"test.com\" class=\"PopupItemLink\">Hey<\/a>

So in Java I use this code

if (asit.matches("(.*)<a href=\\\\\"(.*)\\\\\" class=\\\\\"PopupItemLink\\\\\">(.*)<\\\\\\/a>(.*)")) {
    asit.replaceAll("<a href=\\\\\"(.*)\\\\\" class=\\\\\"PopupItemLink\\\\\"", "$1");
    asit.replaceAll(">(.*)<\\\\\\/a>", "$1");
    return asit;
}

But it doesn't return anything, what's the problem?

I've resolved it removing the if block and write just replaceAll(), reassigning the variable value since Strings are immutable (thanks to @PM77-1)

output = output.replaceAll("<a href=\"(.*)\" class=\"PopupItemLink\"", "$1");
output = output.replaceAll(">(.*)<\\/a>", " ($1)");
return output;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM