java.util.regex.Matcher.group与字符串比较之间的不连续性

时间:2013-10-12 04:46:05

标签: java regex

我想要做的就是将我保存的信息加载到关于JInternalFrame位置的纯文本文件中,并将帧设置为保存为的状态。出于某种原因,我无法将捕获组与字符串进行比较;也就是说,matcher.group("state")与它应该是的字符串("min""max""normal")相比没有返回true,matcher.group("vis")也是如此

String fileArrayStr = "WINDOW_LAYOUT:0,0|779x768|max|show"

我的代码是:

byte[] fileArray = null;
String fileArrayStr = null;
try {
    fileArray = Files.readAllBytes(PathToConfig);
} catch (IOException e) {
    e.printStackTrace();
}
try {
    fileArrayStr = new String(fileArray, "UTF-8");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

// checking the value of fileArrayStr here by outputting it
// confirms the data is read correctly from the file

pattern = Pattern.compile(
    "WINDOW_LAYOUT:\\s*" +
    "(?<x>[0-9\\-]+),(?<y>[0-9\\-]+)\\|" +
    "(?<length>\\d+)x(?<height>\\d+)\\|" +
    "(?<state>[minaxorl]+)\\|" +
    "(?<vis>[showide]+)\\s*");
matcher = pattern.matcher(fileArrayStr);
if (matcher.find()) {
    frame.setLocation(Integer.parseInt(matcher.group("x")),
                    Integer.parseInt(matcher.group("y")));
    frame.setSize(Integer.parseInt(matcher.group("length")),
                    Integer.parseInt(matcher.group("height")));
    DialogMsg("state: " + matcher.group("state") + "\n" + "vis: "
                    + matcher.group("vis"));

    // the above DialogMsg call (my own function to show a popup dialog)
    // shows the
    // data is being read correctly, as the values are "max" and "show"
    // for state
    // and vis, respectively. Same with the DialogMsg calls below.

    if (matcher.group("state") == "min") {
        try {
            frame.setIcon(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    } else if (matcher.group("state") == "max") {
        try {
            frame.setMaximum(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    } else {
        DialogMsg("matcher.group(\"state\") = \""
                        + matcher.group("state") + "\"");
    }
    if (matcher.group("vis") == "show") {
        frame.setVisible(true);
    } else if (matcher.group("vis") == "hide") {
        frame.setVisible(false);
    } else {
        DialogMsg("matcher.group(\"vis\") = \"" + matcher.group("vis")
                        + "\"");
    }
}

代码总是回到else语句。我究竟做错了什么? matcher.group应该返回一个字符串,不是吗?

2 个答案:

答案 0 :(得分:2)

您正在通过“==”运算符比较字符串,该运算符将比较对象,以便条件变为false并进入代码的else部分。因此,代替“==”运算符尝试使用.equals或.equalsIgnoresCase方法。

答案 1 :(得分:1)

更改

if( matcher.group("state") == "min" )

if( matcher.group("state").equals("min") )

您不使用==来比较Strings。您应该使用.equals.equalsIgnoresCase方法。