验证正则表达式中的多个条件 [英] Multiple Conditions in Validation Regex
本文介绍了验证正则表达式中的多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我或多或少是一个正则表达式新手.我试图将以下条件放入正则表达式:
I am more or less a regex novice. I tried to get the following conditions into a regex:
- 字符串开头和结尾没有空格
- 允许所有数字
- 允许空格、点、括号、加号和减号
产生以下正则表达式:
^\S[\d\/. ()\-+]*\S$
但现在我尝试应用另外两个条件:
But now i try to apply two more conditions:
- 只允许一两个 +
- 只允许一个(和一个)
我的问题是如何将这两个条件合并到上面的现有正则表达式字符串中,不包括 + [+]{1,2}
和 () [(]{1} [)]{1}
没有多大意义,因为我尝试不按特定顺序进行一般性陈述,以便能够将其链接起来.谢谢拉尔夫
My problem is how to merge those two conditions into the existing regex string above cuz excluding + [+]{1,2}
and () [(]{1} [)]{1}
doesn't make much sense cuz i try to make general statements in no particular order so that i would be able to chain it. Thanks Ralf
推荐答案
使用这个:
^(?=\S)(?=(?:[^+]*\+){0,2}[^+]*$)(?=(?:[^(]*\()?[^(]*$)(?=(?:[^)]*\))?[^)]*$)[- .()+0-9]*[-.+()0-9]$
在正则表达式演示中,您可以输入检查哪些匹配,哪些不匹配.
In the regex demo you can play with the input to check what matches and doesn't.
说明
^
锚断言我们在字符串的开头- 前瞻
(?=\S)
断言后面的是一个非空格字符 - Lookahead
(?=(?:[^+]*\+){0,2}[^+]*$)
:两个+
字符在大多数 - Lookahead
(?=(?:[^(]*\()?[^(]*$)
:最多一个(
- Lookahead
(?=(?:[^)]*\))?[^)]*$)
:最多一个)
[- .()+0-9]*
零个或多个允许的字符[-.+()0-9]
以允许的非空格字符之一结尾$
锚断言我们在字符串的末尾
- The
^
anchor asserts that we are at the beginning of the string - The lookahead
(?=\S)
asserts that what follows is a non-space character - Lookahead
(?=(?:[^+]*\+){0,2}[^+]*$)
: two+
chars at the most - Lookahead
(?=(?:[^(]*\()?[^(]*$)
: One(
at the most - Lookahead
(?=(?:[^)]*\))?[^)]*$)
: One)
at the most [- .()+0-9]*
zero or more of the allowed chars[-.+()0-9]
end with one of the allowed chars that is not a space- The
$
anchor asserts that we are at the end of the string
参考
这篇关于验证正则表达式中的多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文