简体   繁体   English

Java中的正则表达式可解析字符串

[英]Regular expression in java to parse a string

I have a String. 我有一个琴弦。 The string is "New England 12 Philidelphia 24 (Final)". 字符串是“ New England 12 Philidelphia 24(Final)”。 I need a regaular expression from which i should able to retrieve items like. 我需要一个表达式,我应该可以从中检索类似的内容。

  1. First Team -- New England 一线队-新英格兰
  2. First Team Score -- 12 一队得分-12
  3. Second Team -- Philidelpia 二队-费城
  4. Second Team Score -- 24 二队得分-24
  5. Result -- Final or whatever in the braces. 结果-最终或括号中的任何内容。

Below is a SSCCE showing how to use regex and groups to extract the data you want. 下面是一个SSCCE,显示了如何使用正则表达式和组来提取所需的数据。

FYI, although it will work for just the input you provided, this code will scan through input containing multiple results like this, matching all of them in the while loop. 仅供参考,尽管此代码仅适用于您提供的输入,但此代码将扫描包含多个类似结果的输入,并在while循环中将所有结果匹配。

public static void main( String[] args ) {
    String input = "New England 12 Philidelphia 24 (Final)";
    String regex = "([a-zA-Z ]+)\\s+(\\d+)\\s+([a-zA-Z ]+)\\s+(\\d+)\\s+\\((\\w+)\\)";
    Matcher matcher = Pattern.compile( regex ).matcher( input);
    while (matcher.find( )) {
        String team1 = matcher.group(1);
        String score1 = matcher.group(2);
        String team2 = matcher.group(3);
        String score2 = matcher.group(4);
        String result = matcher.group(5);
        System.out.println( team1 + " scored " + score1 + ", " + team2 + " scored " + score2 + ", which was " + result);
    }
}

Output 输出量

New England scored 12, Philidelphia scored 24, which was Final

用这个:

"(\\w+) (\\d+) (\\w+) (\\d+) \((\\w+)\)"

试试看

^[\D]*\s*\d*\s*[\D]*\s*\d*\s*\([\D]*\)$

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

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