如何编写一个只允许字母、数字和特殊字符的正则表达式,中间永远不会结束 [英] How to Write a Regular Expression that allows only letters, numbers and special characters only i the middle never in the end

查看:14
本文介绍了如何编写一个只允许字母、数字和特殊字符的正则表达式,中间永远不会结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要一些正则表达式的帮助.

Need some regular expressions help.

到目前为止,我的代码允许使用有限数量的特殊字符.但是,我不知道如何让它只允许他们在中间而不是最后.

So far I have my code working to allow a limited number of special characters. However, I don't know how to get it to only allow them in the middle and never the end.

有人可以帮我弄清楚那部分吗?

Can someone help me figure that part out?

这是我在 c# 中使用的代码:

Here is the code I am using in c#:

            Regex uRLToVal= new Regex("^[A-Za-z0-9-_.+!*]*$");

            if (!uRLToVal.IsMatch(this.mainURL))
            {
                results.AddPropertyError("Your Entry can only contain letters, numbers, underscores, periods, plus, exclamation marks and hypens. Special characters should always be inside numbers or letters.  Example: v!v is OK BUT NOT !vv or vv!");
            }

推荐答案

new Regex(@"^[A-Za-z0-9]+([-_.+!*]+[A-Za-z0-9]+)*$");

这意味着:

匹配必须以至少一个数字或字母字符开头:[A-Z-z0-9]+

match must begin with at least one numeric or alpha char:[A-Z-z0-9]+

该序列可能后跟零个或多个特殊字符-_.+!*,后跟至少一个数字或字母字符.第二个组合可以发生零次或多次(例如:asdf-e*r!asdf,或 a 是有效的)

That sequence may be followed by zero or many special chars -_.+!* followed by at least one numeric or alpha char. This second combination can happen zero or many times (example : asdf-e*r!asdf, or a are valid)

这篇关于如何编写一个只允许字母、数字和特殊字符的正则表达式,中间永远不会结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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