每日一道招式:正则表达式实现Mod4
Posted 猿助猿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了每日一道招式:正则表达式实现Mod4相关的知识,希望对你有一定的参考价值。
此招式来源于猿助猿(dadio.xyz) 正则表达式
描述:
Java JDK1.8 起始代码
import java.util.regex.Pattern;
public class Mod {
public static Pattern mod4 = Pattern.compile("...");
}
及简单测试用例
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Mod4Test {
@Test
public void testValidMod4() throws Exception {
String[] validTests = {"[+05620]", "[005624]", "[-05628]", "[005632]", "[555636]", "[+05640]", "[005600]",
"the beginning [-0] the end", "~[4]", "[32]", "the beginning [0] ... [invalid] numb[3]rs ... the end",
"...may be [+002016] will be."};
for(String test : validTests) {
Matcher m = Mod.mod4.matcher(test);
assertTrue(test + " is valid, but no match was made.", m.find());
}
}
@Test
public void testInvalidMod4() throws Exception {
String[] invalidTests = {"[+05621]", "[-55622]", "[005623]", "[~24]", "[8.04]", "No, [2014] isn't a multiple of 4..."};
for(String test : invalidTests) {
Matcher m = Mod.mod4.matcher(test);
assertFalse(test + " is invalid, but a match was made.", m.find());
}
}
}
javascript / node6.11 起始代码
var Mod4 = /.../;
简单测试用例
[ // valid
"[+05620]",
"[005624]",
"[-05628]",
"[005632]",
"[555636]",
"[+05640]",
"[005600]",
"the beginning [-0] the end",
"~[4]",
"[32]",
"the beginning [0] ... [invalid] numb[3]rs ... the end",
"...may be [+002016] will be."
].forEach(function (v) {
Test.expect(Mod4.test(v), JSON.stringify(v) + " is valid, but no match was made.");
});
[ // invalid
"[+05621]",
"[-55622]",
"[005623]",
"[~24]",
"[8.04]",
"No, [2014] isn't a multiple of 4..."
].forEach(function (v) {
Test.expect(!Mod4.test(v), JSON.stringify(v) + " is invalid, but a match was made.");
});
python 2.7/3.4 起始代码
import re
class Mod:
mod4 = re.compile("...") #Your regular expression here
简单测试用例
import re
Test.assert_equals(type(Mod.mod4) == type(re.compile("")), True) #mod4 must be a valid regex object
validTests = ["[+05620]", "[005624]", "[-05628]", "[005632]", "[555636]", "[+05640]", "[005600]",
"the beginning [-0] the end", "~[4]", "[32]", "the beginning [0] ... [invalid] numb[3]rs ... the end",
"...may be [+002016] will be."]
for test in validTests:
Test.assert_equals(Mod.mod4.match(test) is not None, True)
invalidTests = ["[+05621]", "[-55622]",
"[005623]", "[~24]", "[8.04]",
"No, [2014] isn't a multiple of 4..."];
for test in invalidTests:
Test.assert_equals(Mod.mod4.match(test) is not None, False)
欢迎大家通过评论留言说出你的答案。为了能让大家有更好的测试代码的体验,建议大家去猿助猿网站上完成该题。因为图中的测试用例只是一部分简单的测试用例。
觉得此招式有意思?请分享给您好友一起来挑战
以上是关于每日一道招式:正则表达式实现Mod4的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode每日一题2020.6.20 10. 正则表达式匹配