问题
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?
回答1:
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
回答2:
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/*/*/ );
回答3:
You could use the split function with /\*/
. If the length of the returned array is 2, it means that you have a single *.
来源:https://stackoverflow.com/questions/17869299/regular-expression-to-match-a-character-that-can-only-appear-once-in-a-string