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

↘锁芯ラ 提交于 2020-01-15 08:09:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!