我只允许在正则表达式中使用一个连字符 (-) [英] I allow only one hyphen (-) in regex

查看:29
本文介绍了我只允许在正则表达式中使用一个连字符 (-)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,可以在其中获取用户的姓氏.如何在正则表达式中只允许一个连字符 (-)?

I have a text box where i get the last name of user. How do I allow only one hyphen (-) in a regular expression?

^([a-z A-Z]*-){1}[a-z A-Z]*$

推荐答案

你的正则表达式只允许一个 -.但我假设你想 mach "Smith", "Smith-Kennedy", 而不是 "Smith-", 为此你只需将连字符移到第二组:

Your regular expression allow exactly one -. but I assume that you want to mach "Smith", "Smith-Kennedy", but not "Smith-", to do this you just must move the hyphen to the second group:

^[a-z A-Z]+(-[a-z A-Z]+)?$

顺便说一句,在几乎所有使用 * 的情况下,+ 是更好的解决方案.

BTW, in almost all cases when * is used + is the better solution.

这篇关于我只允许在正则表达式中使用一个连字符 (-)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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