正则表达式匹配字符串的一部分,但不匹配整个字符串 [英] Regex matches parts of a string, but not whole string

查看:66
本文介绍了正则表达式匹配字符串的一部分,但不匹配整个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用来验证包含小写和大写字母,数字和破折号的字符串的正则表达式:

This is the regex I'm using to validate a string that can contain lowercase and uppercase letters, numbers and dash:

/([a-zA-Z0-9-])+$/

它具有以下结果:

  • abd - 匹配
  • abcd--匹配
  • abcd0 -匹配
  • abcd0--匹配
  • abc @ -不匹配(正确)
  • abc @ efg -匹配(不正确,不应该)
  • abd - matches
  • abcd- - matches
  • abcd0 - matches
  • abcd0- - matches
  • abc@ - doesn't match (correct)
  • abc@efg - matches (incorrect, it shouldn't)

我在做什么错了?

推荐答案

我会说您需要/^([a-zA-Z0-9-])+ $/.您想匹配整个字符串,而不仅仅是一部分,但是您缺少字符串 ^ 开头的标记.

I would say you need /^([a-zA-Z0-9-])+$/. You want to match the whole string, not just a part, but you're missing the mark for the beginning of the string ^.

^ $ 在字符串的开头和结尾之间说 ([a-zA-Z0-9-])+ 可以有一个或多个字符 a-zA-Z0-9- .

^ and $ say between the beginning and the end of the string and ([a-zA-Z0-9-])+ says there can be one or more characters a-zA-Z0-9-.

您的正则表达式匹配字符串末尾之前包含一个或多个字符的所有内容 a-zA-Z0-9-,无论之前是什么.

Your regexp matches everything which contains one or more characters a-zA-Z0-9- before the end of the string no matter what's before.

您可以在 regex101.com (非常好的在线工具来测试正则表达式)上测试正则表达式测试与解释,参考等).

You can test your regular expression on regex101.com (very good online tool for regular expression testing with explanation, reference etc.).

这篇关于正则表达式匹配字符串的一部分,但不匹配整个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆