簡體   English   中英

Javascript-RegEx大寫和小寫以及混合

[英]Javascript - RegEx Uppercase and LowerCase and Mixed

我有以下代碼:

var cadena = prompt("Cadena:");

document.write(mayusminus(cadena));

function mayusminus(cad){
    var resultado = "Desconocido";

    if(cad.match(new RegExp("[A-Z]"))){
        resultado="mayúsculas";
    }else{
        if(cad.match(new RegExp("[a-z]"))){
            resultado="minúsculas";
        }else{
            if(cad.match(new RegExp("[a-zA-z]"))){
            resultado = "minúsculas y MAYUSCULAS";
            }
        }
    }
    return resultado;
}

我總是有mayusculasminusculas ,從來沒有minusculas y MAYUSCULAS (混合),我正在學習正則表達式,尚不知道我的錯誤:S

new RegExp("[A-Z]")

cadena中的任何字符為大寫字母時匹配。 要在所有字符都大寫時匹配,請使用

new RegExp("^[A-Z]+$")

^迫使它從頭開始, $迫使它從頭開始,而+確保在頭之間有一個或多個[AZ]

我相信您想使用regex模式^[az]+$^[AZ]+$^[a-zA-Z]+$

在正則表達式中,插入符號^匹配字符串中第一個字符之前的位置。 同樣, $匹配字符串中的最后一個字符。 另外, +表示一個或多個事件

如果要確保字符串中沒有其他列出的字符,則必須在模式中使用^$


JavaScript

s = 'tEst';
r = (s.match(new RegExp("^[a-z]+$")))    ? 'minúsculas' :
    (s.match(new RegExp("^[A-Z]+$")))    ? 'mayúsculas' :
    (s.match(new RegExp("^[a-zA-Z]+$"))) ? 'minúsculas y mayúsculas' :
                                           'desconocido';

在此處測試此代碼。

假設cad是foo

// will return false
if (cad.match(new RegExp("[A-Z]"))) {
    resultado="mayúsculas";
// so will go there
} else {
    // will return true
    if (cad.match(new RegExp("[a-z]"))) {
        // so will go there
        resultado="minúsculas";
    } else {
        if (cad.match(new RegExp("[a-zA-z]"))) {
            resultado = "minúsculas y MAYUSCULAS";
        }
    }
}

現在,假設cad是FOO

// will return true
if (cad.match(new RegExp("[A-Z]"))) {
    // so will go there
    resultado="mayúsculas";
} else {
    if (cad.match(new RegExp("[a-z]"))) {
        resultado="minúsculas";
    } else {
        if (cad.match(new RegExp("[a-zA-z]"))) {
            resultado = "minúsculas y MAYUSCULAS";
        }
    }
}

最后,假設cad是FoO

// will return true
if (cad.match(new RegExp("[A-Z]"))) {
    // so will go there
    resultado="mayúsculas";
} else {
    if (cad.match(new RegExp("[a-z]"))) {
        resultado="minúsculas";
    } else {
        if(cad.match(new RegExp("[a-zA-z]"))) {
            resultado = "minúsculas y MAYUSCULAS";
        }
    }
}

如您所見,嵌套的else永遠不會被訪問。

您可以做的是:

if (cad.match(new RegExp("^[A-Z]+$"))) {
    resultado="mayúsculas";
} else if (cad.match(new RegExp("^[a-z]+$"))) {
    resultado="minúsculas";
} else {
    resultado = "minúsculas y MAYUSCULAS";
}

說明:

^表示從字符串的開頭開始

$表示字符串的末尾

<anything>+表示至少一種東西

那就是

^[AZ]+$表示字符串只能包含大寫字符

^[az]+$表示字符串只能包含小寫字符

因此,如果字符串不僅由大寫或小寫字符組成,則字符串包含這兩個字符。

暫無
暫無

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

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