在第二个空格后停止 - 正则表达式不起作用

时间:2017-10-07 03:03:17

标签: java regex

我正在尝试创建一个程序来识别.txt文件中的模式。我希望它记住(“单词”空格“单词”),然后当它击中另一个空格时它会停止。

我已经查找了很多关于模式的例子,但它们似乎都没有用。

这是我的代码:

private void parsing(String line){
    String pattern;
    pattern = "(.*[^\\s]+)"; 
    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(line);
    boolean b = m.matches();
    System.out.println(m.group(0));
}

这是一个输出:

hsad vova 13/12/1995 16/05/2005 01/09/2017 17/03/2018
hsad vova 13/12/1995 16/05/2005 01/09/2017 17/03/2018

P.S。该程序使用BufferedReader从.txt文件中读取此信息。

如果需要,这是完整的代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class insuranceSupport {
   InputStreamReader streamReader =  new InputStreamReader(this.getClass().getResourceAsStream("/database.txt"));
   BufferedReader reader = new BufferedReader(streamReader);
   String thisLine;
      public void getLine(){
           ArrayList<String> list = new ArrayList<String>();
           try {
                while ((thisLine = reader.readLine()) != null){
                    list.add(thisLine);
                    System.out.println(thisLine);
                    parsing(thisLine);
            }
      }    catch (IOException e) {
                e.printStackTrace();
           }

}
    private void parsing(String line){
        String pattern;
        pattern = "(.*[^\\s]+)"; 
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(line);
        boolean b = m.matches();
        System.out.println(m.group(0));
}

}

主要:

public class insuranceMain {
public static void main(String args[]){
    insuranceSupport inc = new insuranceSupport();
    inc.getLine();

}

}

很抱歉这么多信息。我一直在研究这个问题,但找不到解决办法;只是想确保其他人可以解决这个问题。

感谢您的努力和时间!

1 个答案:

答案 0 :(得分:0)

这是提取结果的正则表达式

    Pattern pattern = Pattern.compile("^(\\S+)\\s+(\\S+).*");
    Matcher matcher = pattern.matcher("hsad vova 13/12/1995 16/05/2005 01/09/2017 17/03/2018");
    if (matcher.matches()) {
        System.out.println(matcher.group(1));
        System.out.println(matcher.group(2));
    }

使用拆分

的更简单方法
    String[] strings = "hsad vova 13/12/1995 16/05/2005 01/09/2017 17/03/2018".split("\\s+");
    System.out.println(strings[0]);
    System.out.println(strings[1]);
相关问题