简体   繁体   English

使用模式在Java中解析字符串

[英]Parsing String in Java using a Pattern

I am trying parse out 3 pieces of information from a String . 我正在尝试从String解析出3条信息。

Here is my code: 这是我的代码:

text = "H:7 E:7 P:10";
String pattern = "[HEP]:";

Pattern p = Pattern.compile(pattern);

String[] attr = p.split(text);

I would like it to return: 我希望它返回:

String[0] = "7"
String[1] = "7"
String[2] = "10"

But all I am getting is: 但是我得到的是:

String[0] = ""
String[1] = "7 "
String[2] = "7 "
String[3] = "10"

Any suggestions? 有什么建议么?

A not-so-elegant solution I just devised: 我刚刚设计的一个不太优雅的解决方案:

String text = "H:7 E:7 P:10";
String pattern = "[HEP]:";
text = text.replaceAll(pattern, "");
String[] attr = text.split(" ");

From the javadoc, http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#split(java.lang.CharSequence ) : 在Javadoc中, http ://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#split( java.lang.CharSequence ):

The array returned by this method contains each substring of the input sequence that is terminated by another subsequence that matches this pattern or is terminated by the end of the input sequence. 此方法返回的数组包含输入序列的每个子字符串,该子字符串由与该模式匹配的另一个子序列终止或在输入序列的末尾终止。

You get the empty string first because you have a match at the beginning of the string, it seems. 您似乎首先得到了空字符串,因为在字符串的开头有一个匹配项。

If I try your code with String text = "AH:7 E:7 P:10" I get indeed: 如果我用String text =“ AH:7 E:7 P:10”尝试您的代码,我的确会得到:

A 7 7 10 A 7 7 10

Hope it helps. 希望能帮助到你。

I would write a full regular expression like the following: 我会写一个完整的正则表达式,如下所示:

Pattern pattern = Pattern.compile("H:(\\d+)\\sE:(\\d+)\\sP:(\\d+)");
Matcher matcher = pattern.matcher("H:7 E:7 P:10");
if (!matcher.matches()) {
    // What to do!!??
}
String hValue = matcher.group(1);
String eValue = matcher.group(2);
String pValue = matcher.group(3);

Basing on your comment I take it that you only want to get the numbers from that string (in a particular order?). 根据您的评论,我认为您只想从该字符串中获取数字(按特定顺序?)。

So I would recommend something like this: 所以我建议这样的事情:

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("H:7 E:7 P:10");
while(m.find()) {
    System.out.println(m.group());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM