我有这样的代码:
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;
}我总是有mayusculas或minusculas,从来没有minusculas y MAYUSCULAS (混合),我正在学习regexp,还不知道我的错误:S。
发布于 2012-10-05 12:10:52
new RegExp("[A-Z]")当cadena中的任何字符都是大写字母时匹配.若要匹配所有字符都是大写,请使用
new RegExp("^[A-Z]+$")^强制它在开始时开始,$强制它在末尾结束,+确保在结束之间有一个或多个[A-Z]。
发布于 2012-10-05 12:11:18
我相信您希望使用regex模式^[a-z]+$、^[A-Z]+$和^[a-zA-Z]+$。
在regex中,插入符号^匹配字符串中第一个字符之前的位置。类似地,$在字符串中的最后一个字符之后匹配。另外,+指的是一个或多个事件。
在模式中使用^和$是必要的,如果您想确保字符串中没有其他列出的字符。
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';测试此代码这里。
发布于 2012-10-05 12:17:11
假设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>+至少意味着任何东西。
尽管如此,
^[A-Z]+$意味着字符串应该只包含超感知的字符,
^[a-z]+$意味着字符串应该只包含低胁迫的字符。
因此,如果字符串不只是由超感知或低胁迫的字符组成,则字符串包含这两个字符。
https://stackoverflow.com/questions/12745930
复制相似问题