0

The following is a sample line from a CSV file I'm trying to parse using regex or string.split(","), and I want to extract the year (in below example, 2013). But the problem is: the year column index is not always 17, it could also be 19. I am thinking of looping through the each string in the string.split(",") array and match the pattern against "2XXX".

9344949,HW488429,10/09/2013 05:00:00 AM,039XX W MONROE ST,0610,BURGLARY,FORCIBLE ENTRY,RESIDENCE,false,false,1122,011,28,26,05,1149955,1899326,**2013**,10/16/2013 12:39:00 AM,41.87966141386545,-87.72485045045373,"(41.87966141386545, -87.72485045045373)"

This can break down each line in the CSV file

Pattern.compile("^([^,]+,){2}\\d{2}/\\d{2}/(\\d{4})([^,]+,){3}([^,]+)");

But I need some help matching each string against 2XXX. Tried this: Pattern patt = Pattern.compile("^2\d{3}"); however, my eclipse reports error on this.

4

1 回答 1

1

首先,我强烈建议您尝试使用像 Boris 建议的 CSV 解析器。

如果你必须按照自己的方式做,你可以做类似的事情

String year;
String str = // your csv line
String[] strArr = str.split(",");
for(String s : strArr)
{
    if(s.trim().matches("2\\d{3}"))
    {
        year = s;
        break;
    }
} 
于 2013-10-21T23:16:39.243 回答