匹配单词的正则表达式模式,无需排序

时间:2016-05-31 04:48:33

标签: java regex pattern-matching match string-matching

我正在编写一个测试用例,我的回复可能是以下两种格式之一

<Amount currency="USD" xsi:Type="cc:MoneyType">"10.00"</Amount>

<Amount xsi:Type="cc:MoneyType" currency="USD">"10.00"</Amount>

我找到currency属性值和amount值的代码如下,

Pattern pattern = Pattern.compile("<Amount currency=\"(\\S+)\" xsi:type=\"cc:Money\">(\\S+)</Amount>");
Matcher matcher = null;
Double sumOfAmount = 0.0;
String currency = null;
matcher = pattern.matcher(response);
while(matcher.find()) {
    currency = matcher.group(1);
    sumOfAmount += Double.valueOf(matcher.group(2));
}

但是此代码仅适用于响应的第一种格式,我应该如何将其更改为与第二种格式匹配。换句话说,忽略属性的排序。

2 个答案:

答案 0 :(得分:0)

如果您不需要使用该类型,我认为这个正则表达式应该有效:

"<Amount .*currency=\"(\\S+)\".*>(\\S+)</Amount>"

但如果你需要这种类型,则需要更复杂的方法。

答案 1 :(得分:0)

您可以使用交替使其与订单无关:

<Amount(?:\s+(?:currency="([^"]*)"|xsi:Type="([^"]*)"))+>([^<>]+)</Amount>

...或作为Java字符串文字:

"<Amount(?:\\s+(?:currency=\"([^\"]*)\"|xsi:Type=\"([^\"]*)\"))+>([^<>]+)</Amount>"

但请注意,这个正则表达式是根据您的示例量身定制的,因为在处理XML或HTML时,正则表达式总是必须如此。 (例如,它没有考虑可选的空格,这是许多复杂问题中最简单的。)为了处理XML,你真的应该使用专用的解析器。