Issue with Java string search pattern ( contains / matches)

manjunath ramigani :

I have one string which contains a couple of attribute values. While verifying whether the string contains specific attribute values or not by using some simple regex, the matches function is always returning false value.

Now I need the behavior like,

  1. If String contains \"import\" : Then I need isExportSet to be set as true.
  2. If String contains \"path\" : true Then I need isPathSet to be set to true.

I tried as shown below, but it did not work for me:

public class DriverClass {
    public static void main(String[] args) {
        String str = "\"import\" : \"static\",\"path\" : true";
        boolean isExportSet = str.matches("\\*+export\\*+");
        boolean isPathSet = str.matches("\\*+multipath\\s+:\\s+true");

        System.out.println("Export " + isExportSet);
        System.out.println("Path  " + isPathSet);
    }
}
Another coder :

Please let me know if the following code fulfill the problem deifinition.

static String str = "\"import\" : \"static\",\"path\" : true";

static void test(String str) {
    Map<String, String> map = new HashMap<String, String>();
    String[] parts = str.split("(:|,)");
    for (int i = 0; i < parts.length - 1; i+=2) {
        map.put(getUnquotedStr(parts[i]), getUnquotedStr(parts[i+1]));
    }
    System.out.println(map.size() + " entries: " + map); // 2 entries: {path=true, import=static}
    boolean isExportSet = "".equals(map.get("import"));
    boolean isPathSet = "true".equals(map.get("path"));
    System.out.println(isExportSet + " - " + isPathSet);
}

private static String getUnquotedStr(String str) {
    return str.replaceAll("\"", "").trim();
}

will print as follows on the console:

  • 2 entries: {path=true, import=static}
  • false - true

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=109046&siteId=1