Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re^2: difference in regex

by ovedpo15 (Pilgrim)
on May 29, 2018 at 14:11 UTC ( #1215377=note: print w/replies, xml ) Need Help??

in reply to Re: difference in regex
in thread difference in regex

Thank you for the replay!
As I mentioned on one of the posts on this thread - I would like to split it somehow into two scalars. I can use my ($a,$b) = ($row=~ /(.*),(.*)/); But if $row doesn't have commas it won't work. how do I make always put a string into $path
for example:
if "abc" it will be $path = "abc" and $value is undefined.
if "abc,5" it will be $path = "abc" and $value = 5
if "a,b,c,5" it will be $path = "a,b,c" and $value = 5

Replies are listed 'Best First'.
Re^3: difference in regex
by haukex (Bishop) on May 29, 2018 at 14:30 UTC

    Although personally I'd still use a conditional, of course it's possible to do it all in one regex. One way is by making the comma optional by putting a ? on a group, in this case I'm using a non-capturing (?:...) group, and I had to make the first part of the regex non-greedy so that it doesn't swallow an existing comma:

    use warnings; use strict; use Test::More; my $regex = qr/ ^ (.*?) (?: , ([^,]*) )? $ /x; ok "abc"=~$regex; is $1, "abc"; is $2, undef; ok "abc,5"=~$regex; is $1, "abc"; is $2, 5; ok "a,b,c,5"=~$regex; is $1, "a,b,c"; is $2, 5; done_testing;

    Update: An alternative that says a little more explicitly: either match a string with no commas in it, or, if there are commas, I want to match the thing after the last one: /^ (?| ([^,]*) | (.*) , ([^,]*) ) $/x Update 2: And it turns out this regex is much faster than the above! (try using it in this benchmark)

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1215377]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2022-05-24 03:09 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (82 votes). Check out past polls.