user2620053
user2620053

Reputation: 51

Regular expression to match a character that can only appear once in a string?

I'm looking for a regular expression that will match if the string contains the character *, but only once. It should match a*aa, aa*aaaaa, a*aaaa, but it should not match a**a, a****, ****.

Any advice?

Upvotes: 3

Views: 10525

Answers (3)

fenway
fenway

Reputation: 446

It doesn't appear as though you're capturing any of this string -- so why use a regex to begin with? tr// will return the number of matches:

my $nStars = ( $str =~ tr/*/*/ );

Upvotes: 4

Christophe
Christophe

Reputation: 28114

You could use the split function with /\*/. If the length of the returned array is 2, it means that you have a single *.

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can try this pattern:

^[^*]*\*[^*]*$

Explanations:

^      begining of the string
[^*]*  all characters except * zero or more times
\*     literal *
[^*]*  all characters except * zero or more times
$      end of the string

Upvotes: 12

Related Questions