? or `{0,1}`
will match some pattern when necessary,but now I want to do it reversely.
Say,don't match if necessary.
Anyone get what I mean has the solution?
? or `{0,1}`
will match some pattern when necessary,but now I want to do it reversely.
Say,don't match if necessary.
Anyone get what I mean has the solution?
Just put a question mark after the {0,1}
, as in {0,1}?
, and it will prefer matching zero than one time. The question mark makes it "non-greedy", which means it will not swallow as much as possible.
Test (in Perl):
#! perl
use warnings;
use strict;
my $string = "abcdefghijk";
if ($string =~ /(..{0,1}?)/) {
print "$1\n";
}
Prints
a
You can also use ??
in place of {0,1}?
.
It sounds to me like you're looking for a negative assertion. The syntax for that is usually (?!...)
For example, A(?!B)C
will match A then C, but not if the beginning of C matches B.
?
or{0,1}
will match some pattern when necessary, but now I want to do it reversely.
No, ?
or {0,1}
will match some pattern if possible. Regex is greedy by default.
To make them match when necessary, they need to look like ??
or {0,1}?
.
Seems you already have what you want.
Say, don't match if necessary.
Saying "don't match" is generally something between difficult and impossible in regex. Unless you come up with a real sample of what you need to do, this is hard to answer.