Multiple Conditions in Validation Regex

感情迁移 提交于 2021-02-15 06:54:45

问题


I am more or less a regex novice. I tried to get the following conditions into a regex:

  • No White Space at the beginning and at the end of a string
  • Allow all digits
  • Allow spaces, points, brackets, plus and minus

Resulted in the following regex:

^\S[\d\/. ()\-+]*\S$

But now i try to apply two more conditions:

  • Allow only one or two +
  • Allow only one ( and one )

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


回答1:


Use this:

^(?=\S)(?=(?:[^+]*\+){0,2}[^+]*$)(?=(?:[^(]*\()?[^(]*$)(?=(?:[^)]*\))?[^)]*$)[- .()+0-9]*[-.+()0-9]$

In the regex demo you can play with the input to check what matches and doesn't.

Explanation

  • 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

Reference

  • Lookahead and Lookbehind Zero-Length Assertions
  • Mastering Lookahead and Lookbehind



回答2:


First, get rid of those \S, they are wrong. Each one will match any non-whitespace character, so if for instance I put a $ at the beginning of the phone numer, it will still match.

^[\d\/. ()\-+]+$

Now, let's add some conditions, and for that, we can use lookaheads:

  • One or two +: (?=[^+]*(?:\+[^+]+){0,2}[^+]*$) (non-consecutive and not at the end of a string)
  • One ( and one ): (?=[^()]*(?:\([^()]*\))?[^()]*$)

So the expression becomes:

^(?=[^+]*(?:\+[^+]+){0,2}[^+]*$)(?=[^()]*(?:\([^()]*\))?[^()]*$)[\d\/. ()\-+]+$

Regex101: http://regex101.com/r/xW5pS7/1

This technique lets you basically apply multiple regexes over the same matched string to add constraints. The lookaheads have a $ anchor at the end, so they both have to match the whole string.

But I have a feeling your requiremens are too loose, and this expression will match too much. If you can think of more precise rules, I'll include them in my answer.



来源:https://stackoverflow.com/questions/24922540/multiple-conditions-in-validation-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!