正则表达式使用C#来限制打开和关闭括号只出现一次 [英] Regex to restrict only one occurrence of open and close brackets using C#

查看:410
本文介绍了正则表达式使用C#来限制打开和关闭括号只出现一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确保我不允许多个括号(和)在输入文本?
我有以下的表达,将允许数字,空格,连字符和支架。

How to make sure I don't allow more than one brackets "(" and ")" in the input text? I have the following expression that will allow numbers, spaces, hyphens and brackets.

Regex.Match(text, @"^[0-9 (,),-]+$").Success

我不'吨什么,以允许像((123)456-7891或(91)123-23123(1)的正确字符串可以是:(123)1231231或(121)123-213123

I don't what to allow something like "((123) 456-7891 or (91)123-23123(1). The correct string can be: "(123) 1231231 or (121)123-213123.

编辑:
对不起,不存在明确的要求是只允许数字,空格,连字符和括号(只有一组),具体而言,(应该始终有。一个右括号)。随着你一说,没有括号或一组括号中,如果有人也可以告诉你怎么允许在任何位置的括号不仅在启动?

Edited: Sorry for not being clear. Requirement is to only allow numbers, spaces, hyphens and brackets (one set only). To be specific, "(" should always have a closing bracket ")". As one of you said no paren or one set of paren. If someone can also tell how to allow the paren at any position not only at the start?

推荐答案

这将做到这一点:

@"^(?:[^()]*|[^()]*\([^()]*\)[^()]*)$"

和只允许数字,连字符和空格:

and only allowing numbers, hyphens and spaces:

@"^(?:[-0-9 ]*|[-0-9 ]*\([-0-9 ]*\)[-0-9 ]*)$"

这基本上说,无论有没有括号,或者只能有一组括号中。如果你只想要那个恰好有一组括号的字符串,你可以使用这个简单的形式:

This basically says that either there are no parens, or there can be only one set of parens. If you only want strings that have exactly one set of parens, you can use this simpler form:

@"^[^()]*\([^()]*\)[^()]*$"

和只允许数字,连字符和空格:

and only allowing numbers, hyphens and spaces:

@"^[-0-9 ]*\([-0-9 ]*\)[-0-9 ]*$"

这篇关于正则表达式使用C#来限制打开和关闭括号只出现一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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