简体   繁体   English

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

[英]regexp to allow only one space in between words

I'm trying to write a regular expression to remove white spaces from just the beginning of the word, not after, and only a single space after the word.我正在尝试编写一个正则表达式来删除单词开头的空格,而不是后面的空格,并且单词后面只有一个空格。

Used RegExp:使用的正则表达式:

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

Test 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 

Only one space should be allowed.应该只允许一个空格。 Is it possible?是否可以?

To match, what you need, you can use为了匹配,你需要什么,你可以使用

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

Maybe you could shorten that a bit, but it matches _ as well也许你可以缩短一点,但它也匹配_

var re = /^(\w+\s)*\w+$/;
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(..) is redundant if you use regular expression literal.顺便说一句,如果您使用正则表达式文字,则new RegExp(..)是多余的。

This one does not allow preceding and following spaces plus only one space between words.这个不允许前后空格加上单词之间只有一个空格。 Feel free to add any special characters You want.随意添加您想要的任何特殊字符。

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

demo here演示在这里

Working code- Inside my name.addTextChangedListener() :工作代码 - 在我的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");
            }
        }

You could try adapting this to your code.您可以尝试将其调整为您的代码。

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

Here is a solution without regular expression.这是一个没有正则表达式的解决方案。 Add this script inside document.ready function it will work.将此脚本添加到 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;
            }
            }
        });
const handleChangeText = text => {
    let lastLetter = text[text.length - 1];
    let secondLastLetter = text[text.length - 2];
    if (lastLetter === ' ' && secondLastLetter === ' ') {
      return;
    }
    setInputText(text.trim());
  };

use this用这个

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM