簡體   English   中英

在第二個空格后停止-正則表達式不起作用

[英]Stop after second space - regular expression doesn't work

我正在嘗試制作一個程序來識別.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

PS程序使用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();

}

}

抱歉,這么多信息。 我已經對此進行了很長時間的研究,找不到解決方案。 只是想確保其他人有可能解決此問題。

感謝您的努力和時間!

這是提取結果的正則表達式

    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]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM