简体   繁体   中英

How to remove everything from HTML except special tag in java?

I want to parse HTML String by extracting only <form> ... </form> . All other stuff don't needed and I can remove it.

Today I have some helpers to remove through replaceAll special tag content like:

    /** remove form */
    String newString  = string.replaceAll("(?s)<form.*?</form>", "");       

(?s)<form.*?</form>

removes form tags. But I need vice versa, remove everything except form .

How can I fix it?

See my Gskinner example

Try below code.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Client {

    private static final String PATTERN = "<form>(.+?)</form>";
    private static final Pattern REGEX = Pattern.compile(PATTERN);

    private static final boolean ONLY_TAG = true;

    public static void main(String[] args) {

        String text = "Hello <form><span><table>Hello Rais</table></span></form> end";
        System.out.println(getValues(text, ONLY_TAG));
        System.out.println(getValues(text, !ONLY_TAG));

    }

    private static String getValues(final String text, boolean flag) {
        final Matcher matcher = REGEX.matcher(text);
        String tagValues = null;
        if (flag) {
            if (matcher.find()) {
                tagValues = "<form>" + matcher.group(1) + "</form>";
            }

        } else {
            tagValues = text.replaceAll(PATTERN, "");
        }
        return tagValues;
    }
}

You will get below output

<form><span><table>Hello Rais</table></span></form>
Hello  end

The below code will give you a direction in what you are looking for:

 String str = "<html><form>test form</form></html>";
 String newString  = str.replaceAll("[^<form</form>]+|((?s)<form.*?</form>)", "$1");  
 System.out.println(newString);

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