如果字符串与正则表达式javascript不匹配,则返回True

时间:2016-03-04 17:30:42

标签: javascript regex

我试图写一个函数来确定输入是否是"喊叫"。听到的意思是全部大写。我正在使用的逻辑是

if (this.toUpperCase() === this) 

哪个工作得很好,但是,我遇到的问题是严格的数字或symobolic(?,!等)字符串被标记为喊叫。

我已经尝试过了

的效果
if (this.toUpperCase() === this && !this.match(/a-zA-Z/))

然而,这似乎并没有成功。错误在于我的javascript还是我的正则表达式?在此先感谢您的帮助!

4 个答案:

答案 0 :(得分:3)

您的第二个条件是错误的:您正在检查不包含字母(大写或小写)的字符串。你忘了正则表达式中的方括号。 您应该检查包含至少一个大写字母的字符串:

if ((this.toUpperCase() === this) && (this.match(/[A-Z]/)))

答案 1 :(得分:0)

You can do something like this:

var str = this;
var R = function(regex) {
    return (str.match(regex) || []).length
};
var ratio = {
    upper: R(/[A-Z]/g),
    lower: R(/[a-z]/g),
    letters: R(/[A-Z]/gi),
    spaces: R(/\s/g),
    non_letters: R(/[^A-Z]/gi)
};

and then you can use some logic like:

// if only upper case letters
if (this.length == ratio.upper + ratio.spaces)
    // do something ..

Hope it helps.

答案 2 :(得分:0)

我认为Fabius' answer正是您所寻找的,但我建议对逻辑进行一些更改,因为您最终可能会捕获的内容超过您想要的而不是所有内容:

  • 这就是大战!!
  • Y'
  • 是上面的SHOUTING?
  • 请使用SSCCE。
  • 关于这个?这是在发生什么事吗?

以下是我推荐的内容:



var resultsDiv = $('#results'),
    tests = [
      { string: 'THIS IS SHOUTING!!' },
      { string: 'Y?' },
      { string: 'is the above SHOUTING?' },
      { string: 'Please use SSCCE.' },
      { string: 'wHAT ABOUT THIS? IS THIS SHOUTING?' }
    ];

$.each( tests, function(i, test){
  var string = test.string,
      isShouting;
  
  // First, strip out non-alpha characters:
  string = string.replace(/[^a-z]/ig, '');
  
  var beforeLength = string.length;
  
  // Now remove all uppercase characters:
  string = string.replace(/[^A-Z]/g, '');
  
  var afterLength = string.length;
  
  // Now, compare the length of the before and after, with a threshold for short string.
  // Basically, if the before string is at least 4 characters long and more than half of
  // the string is uppercase, then flag it as "shouting".
  isShouting =
    ( beforeLength >= 4 && ( afterLength / beforeLength >= 0.50 ) );
  
  $('<div>')
    .text(test.string)
    .css('color', 'darkblue')
    .appendTo( resultsDiv );
  
  $('<div>')
    .text(isShouting ? "SHOUTING DETECTED!" : "quiet and controlled.")
    .css('margin-bottom', '15px')
    .css('color', isShouting ? 'red' : 'black')
    .appendTo( resultsDiv );
  
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results">
</div>
&#13;
&#13;
&#13;

你可以摆弄门槛,找到符合你期望的东西。 50%的大写可能过于严格。请记住,任何规则都会有例外,因此请确保&#34;喊叫&#34;不是太麻烦了。

另请注意,我没有做太多的事情来使这个例子国际化。我将其作为练习留给读者。上面的例子足以证明这一理论。

答案 3 :(得分:-2)

您正在询问正则表达式,但您的初始示例并未使用它,因此听起来您正在使用正则表达式来覆盖第一个示例中的错误。

你不需要正则表达式去做你想做的事情。

如果字符串可以保存非字母字符但字母必须全部为大写,请尝试

if (this.toLowerCase() !== this)

支持您可能想要的国际化

if (this.toLocaleLowerCase() !== this)

某些语言具有不同的大小写规则,如文档toLacleLowerCase() doc

中所述
相关问题