我有这样的输入==>
2本书在12.99
4个薯片3.99左右
我想从每一行中提取数值并将它们存储在变量中 例如在行中.. 2本书在12.99我想提取Qauntity = 2和Price = 12.99 来自给定的字符串
答案 0 :(得分:1)
您可以使用:
Pattern p = Pattern.compile("(\\d+)\\D+(\\d+(?:.\\d+)?)");
Matcher mr = p.matcher("4 potato chips at 3.99");
if (mr.find()) {
System.out.println( mr.group(1) + " :: " + mr.group(2) );
}
<强>输出:强>
4 :: 3.99
答案 1 :(得分:0)
(\d+)[^\d]+([+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?)
<强> Debuggex Demo 强>
/^(\d+)[^\d]+([+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?)$/gm
^ Start of line
1st Capturing group (\d+)
\d 1 to infinite times [greedy] Digit [0-9]
Negated char class [^\d] 1 to infinite times [greedy] matches any character except:
\d Digit [0-9]
2nd Capturing group ([+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?)
Char class [+-] 0 to 1 times [greedy] matches:
+- One of the following characters +-
Char class [0-9] 1 to 3 times [greedy] matches:
0-9 A character range between Literal 0 and Literal 9
(?:,?[0-9]{3}) Non-capturing Group 0 to infinite times [greedy]
, 0 to 1 times [greedy] Literal ,
Char class [0-9] 3 times [greedy] matches:
0-9 A character range between Literal 0 and Literal 9
(?:\.[0-9]{2}) Non-capturing Group 0 to 1 times [greedy]
\. Literal .
Char class [0-9] 2 times [greedy] matches:
0-9 A character range between Literal 0 and Literal 9
$ End of line
g modifier: global. All matches (don't return on first match)
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
捕获组1:包含数量
捕获第2组:包含金额
try {
Pattern regex = Pattern.compile("(\\d+)[^\\d]+([+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\\.[0-9]{2})?)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
for (int i = 1; i <= regexMatcher.groupCount(); i++) {
// matched text: regexMatcher.group(i)
// match start: regexMatcher.start(i)
// match end: regexMatcher.end(i)
}
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
注意:这个java只是一个例子,我不用Java编码
答案 2 :(得分:0)
您可以使用MessageFormat课程。以下是工作示例:
MessageFormat f = new MessageFormat("{0,number,#.##} {2} at {1,number,#.##}");
try {
Object[] result = f.parse("4 potato chips at 3.99");
System.out.print(result[0]+ ":" + (result[1]));
} catch (ParseException ex) {
// handle parse error
}