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

Generalizing a REGEX

by Anonymous Monk
on Aug 08, 2020 at 18:55 UTC ( #11120503=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

foreach (@newlist) { $_ =~ s/[.](.*)/($section) }

The above code performs the transform cat.1 ---> cat(1) It also performs the transform ls.so.conf.5 ---> ld(5) # which is WRONG! Is there a way to generalize this regex so it does: cat.1 ---> cat(1) ld.so.conf.5 ---> ld.so.conf(5) Thanks

Replies are listed 'Best First'.
Re: Generalizing a REGEX
by davido (Cardinal) on Aug 08, 2020 at 19:33 UTC

    Your code doesn't compile, and it doesn't explain where $section comes from, which seems relevant since you intend for it to be the replacement portion of a substitution operator.

    Here's an example of a substitution that does what you're asking for based on the example data you provided:

    my @test_cases = ( ['cat.1', 'cat(1)'], ['ld.so.conf.5', 'ld.so.conf(5)'], ); foreach my $test (@test_cases) { my ($string, $want) = @$test; my $transformed = $string =~ s/\.(\d+)$/($1)/r; print "[$string] --> [$transformed] wanted: [$want]. Success: ", ( +$transformed eq $want ? "yes\n" : "no\n"); }

    It's also an example of how to produce an SSCCE. Here's the output it produces:

    [cat.1] --> [cat(1)] wanted: [cat(1)]. Success: yes [ld.so.conf.5] --> [ld.so.conf(5)] wanted: [ld.so.conf(5)]. Success: y +es

    Dave

      Hey Dave Once that regex was fixed, it caused 2 other regex statements to fail. I noticed the '\.' in your statement and was able to fix the other 2 regexes on my own by adding '|\.' to them. ' thought you would like to hear that Thanks again.

      $section is the section number that comes from the manpage. I wanna replace this foreach() loop with something that is more general. I will hack on this and see if I can make it fit. Thanks

Re: Generalizing a REGEX
by haukex (Bishop) on Aug 08, 2020 at 19:02 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://11120503]
Approved by haukex
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2020-09-18 23:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If at first I donít succeed, I Ö










    Results (113 votes). Check out past polls.

    Notices?