Mask
Mask

Reputation: 34197

How to match {1,0} with a regular expression

? or {0,1}

will match some pattern when necessary, but now I want to do it reversely.

Say, don't match if necessary.

What is the solution?

Upvotes: 2

Views: 19774

Answers (4)

Tomalak
Tomalak

Reputation: 338178

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

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

Upvotes: 1

Simon
Simon

Reputation: 25984

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.

Upvotes: 0

user181548
user181548

Reputation:

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

Upvotes: 7

Konamiman
Konamiman

Reputation: 50273

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

Upvotes: 0

Related Questions