【问题标题】:Regex - determine matrix from String正则表达式 - 从字符串确定矩阵
【发布时间】:2011-09-06 10:45:27
【问题描述】:

如何为字符串创建简单的矩阵,可以包含以下组合

123456 ABC    
123456AB1
123456AB12
123456AB123
123456

例如

if ("\\d + \\d + \\d + \\d + \\d + \\d  
   + \\s 
   + [a-zA-Z]+[a-zA-Z]+[a-zA-Z]") {
   //passed variant from input in form 123456 ABC

} else if ("\\d + \\d + \\d + \\d + \\d + \\d 
   + [a-zA-Z]+[a-zA-Z]+[a-zA-Z]
   + \\d") {
   //passed variant from input in form 123456AB1

} else if ("\\d + \\d + \\d + \\d + \\d + \\d 
   + [a-zA-Z]+[a-zA-Z]+[a-zA-Z]
   + \\d + \\d") {
   //passed variant from input in form 123456AB12

} else if ("\\d + \\d + \\d + \\d + \\d + \\d 
   + [a-zA-Z]+[a-zA-Z]+[a-zA-Z]
   + \\d + \\d + \\d") {
   //passed variant from input in form 123456AB123

} else if ("\\d + \\d + \\d + \\d + \\d + \\d") {
   //passed variant from input in form 0123456

} else {
   //doesn't match
}

【问题讨论】:

标签: java regex string


【解决方案1】:

例如,您可以使用以下正则表达式

123456 ABC  -> \\d{6}\\s\\w{3}
123456AB1   -> \\d{6}\\w{3}
123456AB12  -> \\d{6}\\w{4}
123456AB123 -> \\d{6}\\w{5}
123456      -> \\d{6}

if 子句可以在您的示例中使用,例如,

if(str.matches("\\d{6}\\s\\w+") { 
    ... 
} ...

就像您的问题一样,这些正则表达式变体仅涵盖此示例中的确切组合。

【讨论】:

    【解决方案2】:

    如果您需要将输入字符串拆分为相关部分,请尝试以下正则表达式:(\d{6})\s*([a-zA-Z]*)(\d*)

    对于123456AB123,第 1 组为 123456,第 2 组为 AB,第 3 组为 123。 当组丢失时,它们只是一个空字符串。

    请注意,如果变体之间的唯一区别是组(组 1 始终存在,组 2 和组 3 可能为空),则不需要在不同正则表达式上使用 if-else。相反,你可能有这样的东西(伪代码):

    if(matches) {
      groups[3] = extractGroups();
    
      //groups[0] should always exist
    
      if(groups[1] is not empty) {
        ...
      }
    
      if(groups[2] is not empty) {
        ...
      }
    } else {
      handle non-match
    }
    

    【讨论】:

      猜你喜欢
      • 2013-11-13
      • 2015-07-10
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多