Java tutorial
//package com.java2s; import java.util.regex.*; public class Main { protected static Pattern xmlStartPattern = Pattern.compile("^<[\\!\\?]"); protected static Pattern startingElementPattern = Pattern.compile("^\\s*<([a-zA-Z0-9\\-_]+).*"); public static boolean possiblyWellformed(String in) { // extract starting element: in = in.trim(); Matcher startMatcher = xmlStartPattern.matcher(in); if (startMatcher.find()) return true; Matcher m = startingElementPattern.matcher(in); if (!m.matches()) return false; String startingElementName = m.group(1); // check if fragment ends with the corresponding closing pattern: Pattern endPattern = Pattern.compile(".*</" + startingElementName + "\\s*>$"); Matcher endMatcher = endPattern.matcher(in); return endMatcher.matches(); } }