正则表达式测试'*'是否出现在字符串的末尾

时间:2019-07-15 19:46:06

标签: regex

嗨,我对正则表达式不太满意,在这里有点挣扎。我想测试一个字符串,看看它里面是否有'*',它只有一个,并且是字符串中的最后一个字符。

例如

'jflkasjkdfjkslf'  // matches because it has no *
'*'                // matches because it has a * and it is last character
'sdkfjksajdflkj*'  // matches because it has a * and it is last character

'jasldk*aksjdf'  // doesn't match because it has a * and it is not in last position
'asdjflkasjfd**' // doesn't match because it has more than one *
'asdjf*lkasjfd*' // doesn't match because it has more than one *

到目前为止,我(\*)$只是测试它是否以*结尾,所以我还差得远...:(。

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用

^[^*]*\*?$

请参见regex demoregex graph

enter image description here

详细信息

  • ^-字符串的开头
  • [^*]*-除*之外的0个或更多字符
  • \*?-可选的*
  • $-字符串结尾