简体   繁体   English

如何使用正则表达式匹配精确字符串

[英]How to match with an exact string using regular expression

I have small requirement.I want to search a string with exact match. 我的要求很小。我想搜索一个完全匹配的字符串。 Suppose i want to search for None_1, i am searching for 'None_1' using /None_1/, but it is matching even "xxxNone" but my requirement is it should match only None_[any digit]. 假设我想搜索None_1,我正在使用/ None_1 /搜索'None_1',但它甚至匹配“xxxNone”但我的要求是它应该只匹配None_ [任何数字]。 Here is my code 这是我的代码

/^None_+[0-9]{?}/

So it should match only None_1 , None_2 所以它应该只匹配None_1,None_2

You should also anchor the expression at the end of the line. 您还应该将该表达式锚定在该行的末尾。 But that alone will not make it work. 但仅凭这一点就无法发挥作用。 Your expression is wrong. 你的表达是错的。 I think it should be: 我认为它应该是:

/^None_[0-9]+$/
  • ^ matches the beginning of a line ^匹配一行的开头
  • [0-9]+ matches one or more digits [0-9]+匹配一个或多个数字
  • None_ matches None_ None_匹配无None_
  • $ matches the end of a line $匹配一行的结尾

If you only want to match one digit, remove the + . 如果您只想匹配一位数,请删除+


Your original expression /^None_+[0-9]{?}/ worked like this: 您的原始表达式/^None_+[0-9]{?}/工作方式如下:

  • ^ matches the beginning of a line ^匹配一行的开头
  • None matches None None匹配None
  • _+ matches one or more underscores _+匹配一个或多个下划线
  • [0-9] matches one digit [0-9]匹配一位数
  • {? matches an optional opening bracket { 匹配可选的左括号{
  • } matches } }匹配}

尝试这个:

/^None_+[0-9]{?}$/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM