验证字符串仅包含不以数字开头的以空格分隔的字母数字单词
我想使用 preg_match()
,这样给定的字符串中就不应该有特殊字符,例如 @#$%^&/ '
。
例如:
编码
:输出有效:输出无效(以空格开头的字符串)
项目管理
:输出有效(两个单词之间的空格有效)Design23
:输出有效23Designing
:输出无效123
:输出无效
我尝试过,但无法得到有效答案。
I want to use preg_match()
such that there should not be special characters such as @#$%^&/ '
in a given string.
For example :
Coding
: Outputs valid: Outputs Invalid (string beginning with space)
Project management
: Outputs valid (space between two words are valid)Design23
: Outputs valid23Designing
: Outputs invalid123
:Outputs invalid
I tried but could not reach to a valid answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
像这样的正则表达式有帮助吗?
^[a-zA-Z0-9]\w*$
这意味着:
^
= 该模式必须从字符串的开头开始[a-zA -Z0-9]
= 该字符可以是任何字母(az
和AZ
)或数字(0-9
,也请参阅\d
)\w
= 单词字符。这包括字母、数字和空格(默认情况下不是换行符)*
= 重复 0 次或多次$
= 此模式必须在末尾结束string要满足我错过的条件,请尝试这个
^[a-zA-Z0-9]*\w*[a-zA-Z]+\w*$
我添加的额外内容让它第一个字符为数字,但它必须始终包含字母,因为
[a-zA-Z]+
因为+
表示 1 或更多。Does a regex like this help?
^[a-zA-Z0-9]\w*$
It means:
^
= this pattern must start from the beginning of the string[a-zA-Z0-9]
= this char can be any letter (a-z
andA-Z
) or digit (0-9
, also see\d
)\w
= A word character. This includes letters, numbers and white-space (not new-lines by default)*
= Repeat thing 0 or more times$
= this pattern must finish at the end of the stringTo satisfy the condition I missed, try this
^[a-zA-Z0-9]*\w*[a-zA-Z]+\w*$
The extra stuff I added lets it have a digit for the first character, but it must always contain a letter because of the
[a-zA-Z]+
since+
means 1 or more.如果这是家庭作业,您也许应该学习正则表达式:
If this is homework, you maybe should just learn regular expressions:
尝试
Try
要验证字符串是否包含一个或多个字母数字单词(每个单词不以数字开头),请在匹配字母之前使用可重复子模式来匹配可选空格,然后匹配零个或多个字母数字字符。使用后行查找可确保空格不会紧接在字符串的开头。使用
^
和$
锚点确保整个字符串符合条件。代码:(演示)
To validate that a string contains one or more alphanumeric words (each not starting with a digit), use a repeatable subpattern to match an optional space before matching a letter, then zero or more alphanumeric characters. Use a lookbehind to ensure that a space is not immediately at the start of the string. Use
^
and$
anchors to ensure the entire string qualifies.Code: (Demo)