JS:如果某些规则失败,请检查字符串

时间:2016-12-09 11:11:39

标签: javascript arrays regex string

问题

使用正则表达式验证字符串是否与特定规则匹配。

我的问题

我的正则表达似乎没有效果,我也不知道如何检查多个正则表达式的字符串。

示例字符串

This is just a senseless  string with less then 1.000,00 words. and 1 x abbrevations e.g. this one ( and so on).

规则

Every sentence must begin with an upper case character or a number
There must not be a space between number and `x`
Never multiple spaces
There must not be spaces at the beginning and at the end of bracket content

我的正则表达式尝试

/([.?!])\s*(?= [A-Z0-9])/g          // Sentence have to start with upper case
/([0-9]*)(x)/g                      // No space between number and 'x'
/\s{2,}/g                           // Two or more spaces
// don't know how to do last rule

if (/([.?!])\s*(?= [A-Z0-9])/.test(string); )
    failing.push('capitalizeSentence');
else if ...

但也许它可以做得更有活力......

预期结果

我需要知道哪些规则与字符串不匹配(如果有的话)。所以我建议一个数组,其中包含那些规则失败的值。 所以在这个示例字符串中,结果可能是这样的数组,因为每个规则都失败了。

failing = [ 'capitalizeSentence', 'spaceNumber', 'multipleSpaces', 'spaceBrackets' ];

1 个答案:

答案 0 :(得分:1)

这样的事情:

var rules = {
  'capitalizeSentence': /[.?!]\s+[^A-Z\d]/,
  'spaceNumber': /\d\s+x/,
  'multipleSpaces': /\s\s/,
  'spaceBrackets': /\(\s|\s\)/
}
var check = function(str){
  return Object.keys(rules).reduce(function(results,key){
    if(rules[key].test(str)) {
      results.push(key);
    }
    return results;
  },[]);
};
console.log(check('This is just a senseless  string with less then 1.000,00 words. and 1 x abbrevations e.g. this one ( and so on).'));

通过检查规则违规并将这些违规名称添加到返回的数组来进行操作。