0

I'm pretty bad with regex, and tried searching on google, but everything I tried didn't worked.

Here's my code :

@liner = split(/\s+/, $_);
foreach my $v (@liner) {
    if ($v =~ /*.duplex.*/) {
        print ECRIRE ";$v";
    }
}

$v contains something like : "Full-duplex," but can contains other things like "Half-duplex,"....

So I want my condition to match on "any char"duplex"any char".

I tried things like if ($v =~ /(*.)duplex(.*)/)

And some others, but not working. Can anyone help me out?

1
  • 2
    The first *. is invalid - it need's to be .*. Commented Nov 26, 2013 at 13:35

2 Answers 2

3
foreach (split(/\s+/)) {
    print ECRIRE ";$_" if /duplex/i;
}

Luckily, in Perl RegEx are not matched against a whole string, meaning that you don't have to prefix and postfix everything with ".*":

/abcd/

is synonymous to

/.*abcd.*/

(unless you're using a specific option which adds newlines to the matching chars for the dot)

This loop matches on everything duplex in all cases (the /i makes the RegEx case-insensitive).

(Untested, but fingers are crossed)

Sign up to request clarification or add additional context in comments.

2 Comments

Oh god... What a noob i am... Thanks dude for explanations !
That doesn't even compile
-1

The List::MoreUtils module has a firstval function, which will return the first value in a list that satisfies a certain constraint. It is very useful for writing concise and readable code. It is not a core module and you may need to install it.

As others have said, all you need in your regex is /duplex/, as that will check that the string contains the string. You can enhance it with /duplex/i which performs a case-insensitive match instead.

Finally, if you are writing split /\s+/ then you almost certainly want split ' ' instead; that is a literal single-space string, not a regex, and it is the default for split if you don't provide the first parameter. The difference is that, if the target string starts with whitespace then spltting with /\s+/ will return an empty string as the first element of the list, whereas with ' ' it will return just the non-space characters. If you pass no parameters at all to split then it is equivalent to split ' ', $_ which is often what you want.

This short program demonstrates these points.

use strict;
use warnings;

use List::MoreUtils 'firstval';

$_ = 'simplex full-duplex half-duplex';

print firstval { /duplex/ } split;

output

full-duplex

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.