Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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)


In reply to Re^3: difference in regex by haukex
in thread difference in regex by ovedpo15

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (7)
As of 2024-03-28 18:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found