Bernie Perez
Bernie Perez

Reputation: 12573

Regular Expression for CSV with numbers

I'm looking for some regular expression to help parse my CSV file.

The file has lines of

number,number
number,number
Comment I want to skip
number,number
number,number

Ex:

319,5446
564425,87
Text to skip
27,765564

I read each line into a string and I wanted to use some regular express to make sure the line matches the pattern of (number,number). If not then don't use the line.

Upvotes: 2

Views: 5115

Answers (4)

Nhat Nguyen
Nhat Nguyen

Reputation: 678

In general, you can use below RegExp for a comma-separated list of any number of digits:

^\d+(,\d+)*$

Hope this help.

Upvotes: 5

Kyra
Kyra

Reputation: 5407

Which language do you want to do this in? In perl:

read in each line of the csv file and save to $line
if($line !~ m/\d+, \d+/) {
    Do whatever you are going to do with the line with 2 numbers
} 

In Java use this site to help:

 read in each line of the csv file and save to variable line
 Pattern p = Pattern.compile("\d+, \d+"); // remove space if it isn't in file
 Matcher m = p.matcher(line);
 if (m.find()) {
    //it matches
 }

Upvotes: 0

Mikael Svenson
Mikael Svenson

Reputation: 39697

This should match your numbers and line start/end:

^\d+,\d+$

Upvotes: 1

mbeckish
mbeckish

Reputation: 10579

Here is one solution:

^\d+,\d+$

Upvotes: 5

Related Questions