我需要检查的模式是“1w1D1h 1m1s”,但有一些限制,例如每个部分只能有1到3个数字,任何部分都可能丢失,部件之间可以有任何数字或空格和其他空格字符,部件必须是有序的。我为它编写了一个基本正则表达式:
^((?:\s*\d{1,3}[wW]\s*)?(?:\s+\d{1,3}[dD]\s*)?(?:\s+\d{1,3}[hH]\s*)?(?:\s+\d{1,3}[mM]\s*)?(?:\s+\d{1,3}[sS]\s*)?)$现在的问题--我被卡住了,因为如果我写“1D1h”--它不会通过,因为它需要在"1d“之前有一个空格,但是我不能没有那个空间,"1w1d”应该是不正确的。使用regex条件实际上不是一种选择。
发布于 2016-09-28 07:23:30
^((?:\s*\d{1,3}[wW]\s+|\s*\d{1,3}[wW]\s*$)?(?:\s*\d{1,3}[dD]\s+|\s*\d{1,3}[dD]\s*$)?(?:\s*\d{1,3}[hH]\s+|\s*\d{1,3}[hH]\s*$)?(?:\s*\d{1,3}[mM]\s+)?(?:\s*\d{1,3}[sS]\s*|\s*\d{1,3}[sS]\s*$)?)$发布于 2016-09-28 08:42:49
除了@SamjithDasan具有正确的提供之外,您还可以使用ActionScript-3中支持的正则表达式条件词,如果它是一个选项:
var regex: RegExp =
/^(\s*\d{1,3}[wW]\s*(?(?=.)\s+|))?(\d{1,3}[dD]\s*(?(?=.)\s+|))?(\d{1,3}[hH]\s*(?(?=.)\s+|))?(\d{1,3}[mM]\s*(?(?=.)\s+|))?(\d{1,3}[sS]\s*)?$/g;
为了测试它们,以下代码生成所有可能的“真”组合,并根据每个组合检查正则表达式:
var i:uint = 1;
for each(var w: String in ["1w ", ""]) {
for each(var d: String in ["1d ", ""]) {
for each(var h: String in ["1h ", ""]) {
for each(var m: String in ["1m ", ""]) {
for each(var s: String in ["1s ", ""]) {
var str:String = w+d+h+m+s;
var desc:String = strFill(i++ + ". str=\""+str+"\"");
trace(desc+" RegEx-matched: "+(str.match(regex).length == 1 ? "yes" : "no"));
}
}
}
}
}
function strFill(str:String, w:uint = 25, fill:String="."):String {
for (var i:uint=str.length; i<=w; i++) str+=fill; return str;
}产出如下:
1. str="1w 1d 1h 1m 1s ".. RegEx-matched: yes
2. str="1w 1d 1h 1m "..... RegEx-matched: yes
3. str="1w 1d 1h 1s "..... RegEx-matched: yes
4. str="1w 1d 1h "........ RegEx-matched: yes
5. str="1w 1d 1m 1s "..... RegEx-matched: yes
6. str="1w 1d 1m "........ RegEx-matched: yes
7. str="1w 1d 1s "........ RegEx-matched: yes
8. str="1w 1d "........... RegEx-matched: yes
9. str="1w 1h 1m 1s "..... RegEx-matched: yes
10. str="1w 1h 1m "....... RegEx-matched: yes
11. str="1w 1h 1s "....... RegEx-matched: yes
12. str="1w 1h ".......... RegEx-matched: yes
13. str="1w 1m 1s "....... RegEx-matched: yes
14. str="1w 1m ".......... RegEx-matched: yes
15. str="1w 1s ".......... RegEx-matched: yes
16. str="1w "............. RegEx-matched: yes
17. str="1d 1h 1m 1s ".... RegEx-matched: yes
18. str="1d 1h 1m "....... RegEx-matched: yes
19. str="1d 1h 1s "....... RegEx-matched: yes
20. str="1d 1h ".......... RegEx-matched: yes
21. str="1d 1m 1s "....... RegEx-matched: yes
22. str="1d 1m ".......... RegEx-matched: yes
23. str="1d 1s ".......... RegEx-matched: yes
24. str="1d "............. RegEx-matched: yes
25. str="1h 1m 1s "....... RegEx-matched: yes
26. str="1h 1m ".......... RegEx-matched: yes
27. str="1h 1s ".......... RegEx-matched: yes
28. str="1h "............. RegEx-matched: yes
29. str="1m 1s ".......... RegEx-matched: yes
30. str="1m "............. RegEx-matched: yes
31. str="1s "............. RegEx-matched: yes
32. str=""................ RegEx-matched: nohttps://stackoverflow.com/questions/39738297
复制相似问题