簡體   English   中英

正則表達式只允許單詞之間有一個空格

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

我正在嘗試編寫一個正則表達式來刪除單詞開頭的空格,而不是后面的空格,並且單詞后面只有一個空格。

使用的正則表達式:

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

測試示例:

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 

應該只允許一個空格。 是否可以?

為了匹配,你需要什么,你可以使用

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

也許你可以縮短一點,但它也匹配_

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'

順便說一句,如果您使用正則表達式文字,則new RegExp(..)是多余的。

這個不允許前后空格加上單詞之間只有一個空格。 隨意添加您想要的任何特殊字符。

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

演示在這里

工作代碼 - 在我的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");
            }
        }

您可以嘗試將其調整為您的代碼。

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

這是一個沒有正則表達式的解決方案。 將此腳本添加到 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());
  };

用這個

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM