0

我试图弄清楚什么正则表达式将提取这些命名组,每个组都在单独的行上。尝试了不同的组合,但被卡住了。例如,我无法提取 localityDefault 但得到:

有数据假

模式匹配7() 空

public static void main(String[] args) throws Exception {
    String patternOfData = ".*?orgUnit1Default=(?<orgUnit1Default>\\S+)\\s+" +
            "orgUnit2Default=(?<orgUnit2Default>\\S+)\\s+" +
            "organizationDefault=(?<organizationDefault>\\S+)\\s+" +
            "localityDefault=(?<localityDefault>\\S+)\\s+?" +
            "stateDefault=(?<stateDefault>\\S+)\\s+?" +
            "countryDefault=(?<countryDefault>\\S+)\\s+";
    String receivedDataString = "orgUnit1Default=window washers \n"
            + "orgUnit2Default=All Cleaners \n"
            + "organizationDefault=Cleaning Dept \n"
            + "localityDefault=Small Town Here\n"
            + "stateDefault=Washington\n" 
            + "countryDefault=US";
    String toExtractName = "organizationDefault";

    System.out.println("patternMatch7()  "
            + patternMatch7(patternOfData, receivedDataString,
                    toExtractName));
}

static String patternMatch7(String patternOfData,
        String receivedDataString, String toExtractName) throws IOException {
    Pattern dataExtractionPattern;
    dataExtractionPattern = Pattern.compile(patternOfData, Pattern.DOTALL);
    Matcher matcher = dataExtractionPattern.matcher(receivedDataString);
    boolean hasData = false;
    String dataValue = null;
    if (matcher.find()) {
        hasData = true;
        dataValue = matcher.group(toExtractName);
    }
    System.out.println("hasData " + hasData);

    return dataValue;
}
4

2 回答 2

1

我不确定你的数据看起来如何,但你能试试这个正则表达式吗?

String patternOfData = ".*?orgUnit1Default=(?<orgUnit1Default>.+)\\s*\n" +
        "orgUnit2Default=(?<orgUnit2Default>.+)\\s*\n" +
        "organizationDefault=(?<organizationDefault>.+)\\s*\n" +
        "localityDefault=(?<localityDefault>.+)\\s*\n" +
        "stateDefault=(?<stateDefault>.+)\\s*\n" +
        "countryDefault=(?<countryDefault>.+)";
于 2013-09-17T02:30:16.740 回答
0

您的模式假定换行符之前有空格,但局部性在换行符之前没有空格 - 使用 * 而不是 +

+ "organizationDefault=清洁部门\n"
                                    ^ 空格字符

+ "localityDefault=这里的小镇\n"
                                  ^ 没有空格字符...

你为什么不使用 LDAPs 搜索呢?

于 2013-09-17T03:02:06.143 回答