本文介绍了包括“减号”进入这个正则表达式,怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var alphaExp = / ^ [a-zA-ZåäöÅÄÖ\s] + $ / ; 

这是表单验证中的名称字段。



我需要让它可以输入像这样的名字Anna-nicole(注意减号)。
目前减号会导致错误。



我需要重写此正则表达式,以便名称中可以包含负号;最好是我应该让它的名称​​不能以一个减号开始,或以一个结尾。



有人知道怎么做吗?



p> BTW,它是JavaScript。

解决方案

你必须使用反斜线来避开负号。 b

  var alphaExp = / ^ [a-zA-ZåäöÅÄÖ\s\ - ] + $ /; 

要阻止他们在开始或结束时使用它,请尝试如下所示:

  var alphaExp = / ^ [a-zA-ZåäöÅÄÖ\s] + [a-zA-ZåäöÅÄÖ\s\-] * [A-ZA-ZåäöÅÄÖ\s] + $ /; 


I have this regex:

  var alphaExp = /^[a-zA-ZåäöÅÄÖ\s]+$/;

This is for a name-field in a form validation.

I need to make it possible to type names like this "Anna-nicole" (note the minus sign).Currently the minus sign causes error.

I need to remake this regex so that a minus sign can be included in the name; preferably I should make it so that the name also cannot start with a minus sign, or end with one. Only minus signs between "words, or names" should be allowed.

Does anybody know how to do this?

BTW, it is JavaScript.

解决方案

You have to escape the minus sign using backslash.

var alphaExp = /^[a-zA-ZåäöÅÄÖ\s\-]+$/;

To stop them from using it in the beginning or the end, try something like this:

var alphaExp = /^[a-zA-ZåäöÅÄÖ\s]+[a-zA-ZåäöÅÄÖ\s\-]*[a-zA-ZåäöÅÄÖ\s]+$/;

这篇关于包括“减号”进入这个正则表达式,怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 12:46