如何使正则表达式模式的某些部分有条件? [英] How to make some parts of a regex pattern conditional?

查看:55
本文介绍了如何使正则表达式模式的某些部分有条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此论坛上查看了我的问题的答案,但找不到.请专家帮忙.

I checked this forum for a answer to my problem, but couldnt find. Experts please help.

我在验证字符串时遇到问题,比如名字.我得到了一组字符串需要遵守的规则,同样需要用正则表达式确认.我写了一个模式.除了一个规则,我的模式尊重其他一切.我在下面列出了我的正则表达式模式

I have a problem to validate a string say first name. I am given a set of rules which the string needs to honor and the same needs to be confirmed with regex. I wrote a pattern. Except one rule my pattern honors everything else. I am listing my regex pattern below

([A-Za-z]+[-'!` ]?)*

我正在检查一个字符串,比如名字或姓氏,它需要以字母开头,并且可以包含(- 或 ! 或 ' 或 ` 或空格)这 5 个字符中的任何一个,并且仅当有第二个单词时.如果一个名字有 2 个单词,中间有一个空格,那么就可以了.一些例子

I am checking for a string say first or last name which needs to start with a alphabet and can have any one of (- or ! or ' or ` or spaces ) these 5 characters ONE AND ONLY IF there is a second word. If a name has 2 words with a space in between then its ok. some examples

List of Valid Names
TIMOTHY
JONATHON
PATRICK
B`ELLA
SUZY JANE - Only one space allowed
SUZY-JANE

List of Invalid Ones
T~ELLA - Because this ~ is not part of regex
SUZY - JANE - No space allowed between hyphens
SUZY  JANE - 2 spaces betweeb words not allowed
GRACO&LAME - & is not allowed

我的正则表达式通过了上述所有条件,但是当名称以任何一个特殊字符结尾时失败.例如,如果我给 JOHN- OR JOHN' OR JOHN!OR JOHN` OR JOHN(末尾有 s 空格)这些无效,但我的正则表达式无法处理它

My regex passes all these above conditions But fails when the name ends in any one of the special character. For example, if I give JOHN- OR JOHN' OR JOHN! OR JOHN` OR JOHN (with s spaces at the end) these are not valid but my regex isnt able to handle it

有人可以告诉我如何编写条件正则表达式吗?就像一个并且只有当有第二个单词时,正则表达式模式必须允许输入这些特殊字符.

Can some one tell me how to write a conditional regex? Like one and only if there is a second word then the regex pattern must allow the entry of these special characters.

推荐答案

试试这个

[A-Za-z]+(?:[-'!` ]?[A-Za-z]+)?

您可以在此处在线查看:regexr

You can check it online here: regexr

第二部分

(?:[-'!` ]?[A-Za-z]+)? 

是一个非捕获组,这个组是因为最后的?是可选的.

is a non capturing group, this group is because of the ? at the end optional.

这篇关于如何使正则表达式模式的某些部分有条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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