[英]Regex to match all alphanumeric and certain special characters?
I am trying to get a regex to work that will allow all alphanumeric characters (both caps and non caps as well as numbers) but also allow spaces, forward slash (/), dash (-) and plus (+)? 我正在尝试使一个正则表达式能够工作,以允许所有字母数字字符(大写和非大写以及数字)但也允许空格,正斜杠(/),破折号(-)和加号(+)?
I have been playing with a refiddle: http://refiddle.com/gqr but so far no success, anyone any ideas? 我一直在玩一个改装: http: //refiddle.com/gqr但到目前为止还没有成功,任何人有什么想法?
I'm not sure if it makes any difference but I am trying to do this in c#? 我不确定它是否有任何区别,但是我正在尝试在C#中执行此操作?
If you want to allow only those, you will also need the use of the anchors ^
and $
. 如果只允许这些,则还需要使用锚^
和$
。
^[a-zA-Z0-9_\s\+\-\/]+$
^ ^^
This is your regex and I added characters as indicated from the second line. 这是您的正则表达式,我在第二行中添加了字符。 Don't forget the +
or *
near the end to allow for more than 1 character (0 or more in the case of *
), otherwise the regex will try to match only one character, even with .Matches
. 不要忘记末尾附近的+
或*
以允许超过1个字符(在*
的情况下为0或更多),否则正则表达式将尝试仅匹配一个字符,即使是.Matches
。
You can also replace the whole class [A-Za-z0-9_]
by one \\w
, like so: 您还可以将整个类[A-Za-z0-9_]
替换为\\w
,如下所示:
^[\w\s\+\-\/]+$
EDIT: 编辑:
You can actually avoid some escaping and avoid one last escaping with a careful placement (ie ensure the -
is either at the beginning or at the end): 实际上,您可以避免一些转义并避免最后一次转义,并小心放置(即确保-
在开头或结尾):
^[\w\s+/-]+$
Your regex would look something like: 您的正则表达式如下所示:
/[\w\d\/\-\+ ]+/g
That's all letters, digits, and / - + and spaces (but not any other whitespace characters) 这是所有字母,数字和/ - +和空格(但不是任何其他空白字符)
The + at the end means that at least 1 character is required. 末尾的+表示至少需要1个字符。 Change it to a * if you want to allow an empty string. 如果要允许使用空字符串,请将其更改为*。
This code does that: 此代码执行以下操作:
var input = "Test if / this+-works&sec0nd 2 part*3rd part";
var matches = Regex.Matches(input, @"([0-9a-zA-Z /+-]+)");
foreach (Match m in matches) if (m.Success) Console.WriteLine(m.Value);
And output will have 3 result lines: 输出将有3条结果行:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.