0
$str="!bypass";

I need return string that only start with regex "!" How can I return bypass ?

1
  • What do you mean? Do you want to remove the exclamation mark from the beginning of a string? Commented Jun 1, 2017 at 7:52

2 Answers 2

3

To match strings that start with a ! you need this pattern. The ^ is the anchor at the beginning of the string.

/^!/

If you want to capture the stuff after the !, you need this pattern. The parenthesis () are a capture group. They tell Perl to grab everything between them and keep it. The . means any character, and the + is a quantifier for as many as possible, at least one. So .+ means grab everything.

/^!(.+)/

To apply it, do this.

$str =~ m/^!(.+)/;

And to get the "bypass" out of that pattern, use the $1 match variable that was assigned automatically by Perl with the m// operation.

print $1; # will print bypass

To make that conditional, it would be:

print $1 if $str =~ m/^!(.+)/;

The if here is in post-fix notation, which lets you omit the block and the parenthesis. It's the same as the following, but shorter and easier to read for single statements.

if ( $str =~ m/^!(.+)/ ) {
    print $1;
}

If you want to permanently change $str to not have an exclamation mark at the beginning, you need to use a substitution instead.

$str =~ s/^!//;

The s/// is the substitution operator. It changes $str in place. The original value including the ! will be lost.

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

Comments

1

Use ^!\K.+.

It works this way:

  • ^! - Match initial ! (but this will soon change, see below).
  • \K - Keep - "forget" about what you have matched so far and set the starting point of the match here (after the !).
  • .+ - Match non-empty sequence of chars.

Due to \K, only the last part (.+) is actually matched.

3 Comments

How would you use the match with \K in an actual program? What would the logic around it be?
You can program it e.g. as follows: my $str="!bypass"; if ($str =~ /^!\K.+/) { print "Match: $&\n"; } else { print "No match\n"; } Of course, the matched content is after \K.
You should add that to your answer. It's a more advanced technique, and I actually didn't know the \K.

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.