[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 238
  • Last Modified:

Reg Ex to parse CSV

Hi,

Can someone provide me with a regex for the following example, where I need to store every character before the first comma, and ignore the rest.

EXAMPLE STRING
abcde,fghijk,lmnop
RESULT
abcde

Thanks!
0
mullykid
Asked:
mullykid
  • 4
  • 3
  • 3
  • +2
2 Solutions
 
Marco GasiFreelancerCommented:
if in your example you want the string abcde only and you're using php then use this:

preg_match('/^\w*(?=,)/i', $subject, $match);

echo $match[0];

Cheers
0
 
mullykidAuthor Commented:
Yes, just the bunch of characters before the first comma

So, this is it:

^\w*(?=,)/i
0
 
mullykidAuthor Commented:
Hi,

No. It didn't work. :(
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Marco GasiFreelancerCommented:
What language you're using? And what you get with regex above?
0
 
mullykidAuthor Commented:
Perl.
0
 
Marco GasiFreelancerCommented:
Sorry for the delay. I didn't solve your question using only a regex, but if you can get file contents in a variable and process it line by line, the regex I provided should work. Waiting for other answers, you could try this...

Cheers
0
 
käµfm³d 👽Commented:
So, this is it:

^\w*(?=,)/i
For the most part... you just need to add the beginning pattern delimiter if you didn't do so. For example:

$input = "abcde,fghijk,lmnop";

if ($input =~ /^(\w*)(?=,)/i) {
        print "$1\n";
}

Open in new window

0
 
käµfm³d 👽Commented:
P.S.

You don't need the trailing "i". It won't hurt anything if you leave it in, but it doesn't add anything to the pattern either.
0
 
käµfm³d 👽Commented:
An even simpler pattern would be:

$input = "abcde,fghijk,lmnop";

if ($input =~ /^([^,]*)/) {
        print "$1\n";
}

Open in new window

0
 
parparovCommented:
#!perl

my $aa = 'abcd,efgh,klmn';

$aa =~ /^(?:(.*?)\,)/;
print "1 $1\n";

Open in new window

0
 
tel2Commented:
Hi parprov,
Why are you escaping the comma, and why are you printing "1 " in front of the output?


Try this, mullykid

#!/usr/bin/perl

my $input = 'abcd,efgh,klmn';

$input =~ /^(.*?),/;
print "$1\n";
0
 
parparovCommented:
tel2: so that you could ask
0
 
tel2Commented:
Hi parparov,
That worked.
Why did you want me to ask?
0
 
mullykidAuthor Commented:
thanks guys for ur help!! I will awared points soon.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 3
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now