使用正则表达式

时间:2016-03-03 12:44:06

标签: java regex xml

某些服务让我无效xml。 例如:

<?xml version="1.0" encoding="UTF-8"?>
<root>
     <123>PHONE</123>
</root>

对于解析我正在使用java SAX解析器并尝试解析此xml时出现异常。

所以我想创建替换&lt; 123&gt;的正则表达式。到&lt; _123&gt;。 我尝试了不同的表达但没有成功。

我尝试过类似的事情:

searchResponse = searchResponse.replaceAll("([^</>]*)\\d([^>]*)", "_$0");

但它无效

2 个答案:

答案 0 :(得分:0)

这看起来很有用:

https://github.com/branaway/Japid/blob/master/src.japidplay/cn/bran/play/routing/ParamSpec.java#L21

String format = "[^/]+"; // the default regex
Class<?> type;
static final String varNamePatternText = "[a-zA-Z_$][a-zA-Z_$0-9]*";
static final String paramSpecPatternText = "(<(.+)>)?" + "(" + varNamePatternText + ")";
static final Pattern paramSpecPattern = Pattern.compile(paramSpecPatternText);

/**
 * @param s
 */
public ParamSpec(String s) {
    String[] ex = extract(s);
    name = ex[0];
    format = ex[1];
    formatPattern = Pattern.compile(format);
}

public static String[] extract(String s) {
    Matcher matcher = paramSpecPattern.matcher(s);
    if (matcher.find()) {
        String form = matcher.group(2);
        form = form == null ? "" : form;
        String var = matcher.group(3);
        return new String[] { form, var };
    }
    throw new RuntimeException("param spec does not match the pattern: " + paramSpecPatternText
            + ". The input is: " + s);
}

答案 1 :(得分:0)

我找到了一个对你有帮助的例子。

private boolean acceptPath(String path) {
    if(goodPaths.isEmpty())
        return true;
    //If no path in filter, return true
    boolean valid = true;
    for(Pattern pathp : goodPaths) {
        valid = pathp.matcher(path).find();
        if(valid)
            break;
    }
    return valid;
}

此处的完整代码:http://code.openhub.net/file?fid=YNJFXZrLcZ6-dCCvz9HbeTu5AbQ&cid=RNO7S9fwx24&s=Match%20xml%20tag%20name%20using%20regular%20expression&pp=0&fl=Java&ff=1&filterChecked=true&fp=3212&mp,=1&ml=0&me=1&md=1&projSelected=true#L0