Java中的模式和匹配器

时间:2013-12-09 12:07:00

标签: java

我是Java新手。我搜索谷歌,无法得到任何东西。请帮我。 我希望从我的句子中得到这个。

  

1 - 超值自然硬木烟熏培根
  2-2
  3-18

我写不出resultRegexString

public class Test {
    public static void main(String[] args) {

        String currentString = "Title:Great Value Naturally Hardwood Smoked Bacon,Quantity: 2, Price: $18";
        String resultRegexString = "Title\\: ([^,]+), Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";
        Pattern resultRegexPattern = Pattern.compile(resultRegexString);
        Matcher resultRegexMatcher = resultRegexPattern.matcher(currentString);
        if(resultRegexMatcher.find()){
             System.out.println(resultRegexMatcher.group(1));
            System.out.println(resultRegexMatcher.group(2));
            System.out.println(resultRegexMatcher.group(3));
    }
        else {
            System.out.println("hello");
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我认为这是格式化问题。删除正则表达式中的空格或在输入字符串中添加空格。

String currentString = "Title: Great Value Naturally Hardwood Smoked Bacon, Quantity: 2, Price: $18";
String resultRegexString = "Title\\: ([^,]+), Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";

String currentString = "Title:Great Value Naturally Hardwood Smoked Bacon,Quantity: 2, Price: $18";
String resultRegexString = "Title\\:([^,]+),Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";

答案 1 :(得分:0)

首先在,上拆分,然后在:上拆分每个键值对。这个的自然结构是Map

public static void main(String[] args) throws Exception {
    String currentString = "Title:Great Value Naturally Hardwood Smoked Bacon,Quantity: 2, Price: $18";
    final Map<String, String> parsed = new LinkedHashMap<>();
    for (final String s : currentString.split("\\s*+,\\s*+")) {
        final String[] keyValuePair = s.split("\\s*+:\\s*+", 2);
        parsed.put(keyValuePair[0], keyValuePair[1]);
    }
}

我在拆分周围添加了空格,因此无需trim()。地图现在包含:

{Title=Great Value Naturally Hardwood Smoked Bacon, Quantity=2, Price=$18}

您可以使用以下方式拆分所需的输出:

    final Iterator<String> values = parsed.values().iterator();
    for (int i = 1; values.hasNext(); ++i) {
        System.out.println(i + " - " + values.next());
    }

输出:

1 - Great Value Naturally Hardwood Smoked Bacon
2 - 2
3 - $18