简体   繁体   English

如何将这个确切的短语与regex匹配?

[英]How can I match this exact phrase with regex?

See it in action! 观看实际操作!

HTML: HTML:

<input type='text' value="2012-12-30 Morning">
<input type='text' value="2012-12-30 Lunch">
<input type='text' value="2012-12-30 Dinner">
<input type='text' value="2012-12-30 Either akgalkgalkgla">
<input type='text' value="2012-12-30">
<input type='text' value="Morning">
<button>Check</button>

Javascript/jQuery: Javascript / jQuery:

$("button").click(function() {
    $("input")
        .filter(function() {
            return this.value.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}\s[A-Za-z]+/);
        })
        .css("border", '1px solid red');

})​

I tried using the anchors ^ and $ but it doesn't match it anymore. 我尝试使用锚^$但不再匹配。 In the above example, it should NOT match "2012-12-30 Either akgalkgalkgla" 在上面的示例中,它不应该匹配“ 2012-12-30 akgalkgalkgla”

Here's the regex [0-9]{4}-[0-9]{2}-[0-9]{2}\\s[A-Za-z]+ 这是正则表达式[0-9]{4}-[0-9]{2}-[0-9]{2}\\s[A-Za-z]+

2012-12-30 Morning
2012-12-30 Lunch
2012-12-30 Dinner
2012-12-30 Either akgalkgalkgla

Update: 更新:

So ^[0-9]{4}-[0-9]{2}-[0-9]{2}\\s[A-Za-z]+$ does work. 因此^[0-9]{4}-[0-9]{2}-[0-9]{2}\\s[A-Za-z]+$确实有效。 I was initially trying this on regexpal, and it didn't seem to work... 我最初是在正则表达式上尝试此操作,但似乎没有效果...

Adding the anchors seems to work perfectly for preventing partial matches. 添加锚点似乎可以很好地防止部分匹配。 The contents of the first three inputs are matched, the last three are not: 前三个输入的内容匹配,后三个输入不匹配:

$("button").click(function() {
    $("input")
        .filter(function() {
            return this.value.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}\s[A-Za-z]+$/);
        })
        .css("border", '1px solid red');
});

Here it is in action: http://jsfiddle.net/ZZYMG/4/ 它在起作用: http : //jsfiddle.net/ZZYMG/4/

If you want to apply the border to all the elements that fail this test, simply invert the boolean you are returning in the filter callback: 如果你想在边境适用于所有失败本次测试的元素,只需翻转你在过滤器中的回调都返回布尔:

return !this.value.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}\s[A-Za-z]+$/);

Using anchors works as expected. 使用锚点按预期方式工作。 Are you sure you had the anchors in the right places? 您确定在正确的地方安装了锚点吗?

/^[0-9]{4}-[0-9]{2}-[0-9]{2}\s[A-Za-z]+$/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM