验证正则表达式中的多个条件

编程入门 行业动态 更新时间:2024-10-17 11:32:15
本文介绍了验证正则表达式中的多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我或多或少是一个正则表达式新手.我试图将以下条件放入正则表达式:

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

参考

  • 前瞻和后视零长度断言
  • 掌握前瞻和后视

更多推荐

验证正则表达式中的多个条件

本文发布于:2023-11-22 14:42:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617853.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   条件   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!