Javascript 为匹配/不匹配的正则表达式返回真/假

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7052797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:37:07  来源:igfitidea点击:

Return true/false for a matched/not matched regex

javascriptregex

提问by markzzz

I have this regex on Javascript

我在 Javascript 上有这个正则表达式

var myS = "00 - ??:??:?? - a";
var removedTL = myS.match(/^(\d\d) - (\?\?|10|0\d):(\?\?|[0-5]\d):(\?\?|[0-5]\d) - (.*)/);

and I need to return "false" if mySis not in that format, true otherwise.

如果myS不是那种格式,我需要返回“false” ,否则返回true。

I mean :

我的意思是 :

var myS = "00 - ??:??:?? - a";  // TRUE
var myS = "00 - ??:?:?? - a";   // FALSE

how can I check if the regex has matched the string or not?

如何检查正则表达式是否与字符串匹配?

采纳答案by Leslie Hanks

The matchmethod will return nullif there is no match.

如果没有匹配,该match方法将返回null

回答by Lightness Races in Orbit

The more appropriate function here might be RegExp.test, which explicitly gives you true or false.

这里更合适的函数可能是RegExp.test,它明确地为您提供 true 或 false

console.log(/lolcakes/.test("some string"));
// Output: false

console.log(/lolcakes/.test("some lolcakes"));
// Output: true

回答by user113716

Use a double logical NOT operator.

使用双逻辑非运算符

return !!removedTL;

This will convert to true/falsedepending on if matches are found.

这将转换为true/false取决于是否找到匹配项。

No matches gives you null, which is converted to false.

没有匹配项给你null,它被转换为false.

One or more matches gives you an Array, which is converted to true.

一个或多个匹配项为您提供一个数组,该数组将转换为true.



As an alternative, you can use .test()instead of .match().

作为替代方案,您可以使用.test()代替.match()

/^(\d\d) - (\?\?|10|0\d):(\?\?|[0-5]\d):(\?\?|[0-5]\d) - (.*)/.test( myS );

...which gives you a boolean result directly.

...直接给你一个布尔结果。

回答by Megamind Saiko

var myS = "00 - ??:??:?? - a";
var patt = new RegExp("^(\d\d) - (\?\?|10|0\d):(\?\?|[0-5]\d):(\?\?|[0-5]\d) - (.*)");
var removedTL = patt.test(myS);

removedTL will hold a boolean value true if matched, false if not matched

如果匹配,removedTL 将保存一个布尔值 true,如果不匹配,则为 false

回答by SpikePy

Since I also prefer using matchyou could do the following workaround to get a Boolean result:

由于我也更喜欢使用match,您可以执行以下解决方法来获得布尔结果:

var myS = "00 - ??:??:?? - a"
var removedTL = myS.match(/^(\d\d) - (\?\?|10|0\d):(\?\?|[0-5]\d):(\?\?|[0-5]\d) - (.*)/) != null