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