tags:

views:

80

answers:

4
? 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?

A: 

So, you need "two or more"? Then try this: {2,}

Konamiman
nope,you missed my point.
Mask
+4  A: 

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}?.

Kinopiko
@Lukas: Thank you for your additions to my answer.
Kinopiko
But what I want is to make it greedy,match if possible.
Mask
I want it to prefer matching one than zero time.
Mask
That's what `?` and `{0,1}` do *by default*. Regex is greedy unless noted otherwise. `?` and `{0,1}` do match if *possible*, not if *necessary* (as you stated).
Tomalak
A: 

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.

Simon
A: 

? 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.

Tomalak