正则表达式只允许单词之间的一个空格

时间:2014-02-12 08:09:33

标签: javascript regex

我正在尝试编写一个正则表达式来从单词的开头处删除空格,而不是在单词后面的单个空格中删除空格。

使用RegExp:

var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/);

测试Exapmle:

1) test[space]ing - Should be allowed 
2) testing - Should be allowed 
3) [space]testing - Should not be allowed 
4) testing[space] - Should be allowed but have to trim it 
5) testing[space][space] - should be allowed but have to trim it 

只允许一个空格。可能吗?

8 个答案:

答案 0 :(得分:12)

要匹配,您需要什么,您可以使用

var re = /^([a-zA-Z0-9]+\s)*[a-zA-Z0-9]+$/;

也许你可以缩短一点,但它也匹配_

var re = /^(\w+\s)*\w+$/;

答案 1 :(得分:7)

function validate(s) {
    if (/^(\w+\s?)*\s*$/.test(s)) {
        return s.replace(/\s+$/, '');
    }
    return 'NOT ALLOWED';
}
validate('test ing')    // => 'test ing'
validate('testing')     // => 'testing'
validate(' testing')    // => 'NOT ALLOWED'
validate('testing ')    // => 'testing'
validate('testing  ')   // => 'testing'
validate('test ing  ')  // => 'test ing'

BTW,如果您使用正则表达式文字,new RegExp(..)是多余的。

答案 2 :(得分:1)

这个不允许前后空格加上单词之间只有一个空格。随意添加您想要的任何特殊字符。

^([A-Za-z]+ )+[A-Za-z]+$|^[A-Za-z]+$

demo here

答案 3 :(得分:0)

var f=function(t){return Math.pow(t.split(' ').length,2)/t.trim().split(' ').length==2}

f("a a")
true
f("a a ")
false
f("a  a")
false
f(" a a")
false
f("a a a")
false

答案 4 :(得分:0)

这是一个没有正则表达式的解决方案。 在document.ready函数中添加此脚本,它将起作用。

var i=0;
        jQuery("input,textarea").on('keypress',function(e){
            //alert();
            if(jQuery(this).val().length < 1){
                if(e.which == 32){
                    //alert(e.which);
                return false;
                }   
            }
            else {
            if(e.which == 32){
                if(i != 0){
                return false;
                }
                i++;
            }
            else{
                i=0;
            }
            }
        });

答案 5 :(得分:0)

工作代码 - 在name.addTextChangedListener()内:

public void onTextChanged(CharSequence s, int start, int before, int count) {
            String n = name.getText().toString();
            if (n.equals(""))
                name.setError("Name required");
            else if (!n.matches("[\\p{Alpha}\\s]*\\b") | n.matches(".*\\s{2}.*") | n.matches("\\s.*")) {
                if (n.matches("\\s.*"))
                    name.setError("Name cannot begin with a space");
                else if (n.matches(".*\\s{2}.*"))
                    name.setError("Multiple spaces between texts");
                else if (n.matches(".*\\s"))
                    name.setError("Blank space at the end of text");
                else
                    name.setError("Non-alphabetic character entered");
            }
        }

您可以尝试将其改编为您的代码。

答案 6 :(得分:0)

const handleChangeText = text => {
    let lastLetter = text[text.length - 1];
    let secondLastLetter = text[text.length - 2];
    if (lastLetter === ' ' && secondLastLetter === ' ') {
      return;
    }
    setInputText(text.trim());
  };

答案 7 :(得分:-1)

使用此

^([A-Za-z]{5,}|[\s]{1}[A-Za-z]{1,})*$

演示:-{https://regex101.com/r/3HP7hl/2

相关问题