具有空格的特定模式的正则表达式

时间:2016-09-28 04:51:56

标签: regex actionscript-3

我需要检查的模式是" 1w 1d 1h 1m 1s",有一些限制,例如每个部分只能有1到3个数字,任何部分都可以丢失,可以有零件之间的任何数字或空格以及其他空白字符,零件必须按顺序排列。我为它写了一个基本的正则表达式:

trying to get non-object property

现在问题 - 我卡住了,因为如果我写了#1; 1d 1h" - 它不会通过,因为它需要一个空间" 1d",但我不能拥有那个空间," 1w1d"应该是不正确的。使用正则表达式条件并不是一种选择。

2 个答案:

答案 0 :(得分:1)

^((?:\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}[m‌​M]\s+)?(?:\s*\d{1,3}‌​[sS]\s*|\s*\d{1,3}[s‌​S]\s*$)?)$

答案 1 :(得分:1)

除了@SamjithDasan正确provided之外,您还可以使用ActionScript-3支持的正则表达式conditionals,如果它是一个选项:

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: no