2016-02-06 86 views
-3

一些特殊字符目前我有这个正则表达式不允许在出发空间,并允许在中间

^[^a-zA-Z0-9\\-\\s]+$ 

表达,但它允许特殊字符。我只想让这些[- .,$% ]中间的字符。

+0

尝试['^ \ S [A-ZA-Z0-9。, $%\ s-] * $'](https://regex101.com/r/vP3tT0/3) – Tushar

+0

尝试'^ [a-zA-Z0-9] +(?:[ - 。,$%] [ a-zA-Z0-9] +)* $''' –

回答

0

您可以使用negative lookahead assertion

$('#input').on('input', function(i, v) { 
 
    $(this).css('color', /^(?!((^[- .,$%].*)|(.*[- .,$%]$)))[^a-zA-Z0-9\-\s]+$/.test(this.value) ? 'green':'red'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input id="input" />

Regex explanation

^(?!((^[- .,$%].*)|(.*[- .,$%]$)))[^a-zA-Z0-9\-\s]+$ 

Regular expression visualization

+0

不工作pranav ....谢谢你的答案请给我建议更多 – Ganesh

+0

@Ganesh请加上有效和无效的字符串 –

0

这不会让空间&也将允许提特殊字符

^[[email protected]/#&+-\[\]$%]*$ 

对于允许之间而不是在开始

^[^-\s][a-zA-Z0-9_\[email protected]/#&+-\[\]$%]+$ 
+0

不工作......... ......请给我建议更多 – Ganesh

+0

/^ [^ - \ S] [a-zA-Z0-9_ \ s-。 /&\ [\] $%] + $ /它正在工作,但允许中间的所有特殊字符 – Ganesh

+0

所以现在的实际问题是什么?我的意思是它应该允许的地方? 会好的,如果ü提供一个有效的和无效的一个参考串 –