【问题标题】:Regex to filter strings正则表达式过滤字符串
【发布时间】:2012-10-13 06:26:09
【问题描述】:

我需要根据两个要求过滤字符串

1) 它们必须以“city_date”开头

2) 它们不应在字符串中的任何位置包含“metro”。

只需一次检查即可完成。

一开始我知道应该是这样,但不知道用“metro”消除字符串

string pattern = "city_date_"

补充:我需要使用正则表达式来执行 SQL LIKE 语句。因此我需要它在一个字符串中。

【问题讨论】:

标签: c++ regex string pattern-matching


【解决方案1】:

通过使用 javascript

input="contains the string your matching"

var pattern=/^city_date/g;
if(pattern.test(input))  // to match city_data at the begining
{
var patt=/metro/g;
if(patt.test(input)) return "false";  
else return input; //matched string without metro
}
else
return "false"; //unable to match city_data

【讨论】:

    【解决方案2】:

    正则表达式通常比直接比较昂贵得多。如果直接比较可以轻松表达需求,请使用它们。这个问题不需要正则表达式的开销。直接写代码:

    std::string str = /* whatever */
    const std::string head = "city_date";
    const std::string exclude = "metro";
    if (str.compare(head, 0, head.size) == 0 && str.find(exclude) == std::string::npos) {
        // process valid string
    }
    

    【讨论】:

      【解决方案3】:

      使用negative lookahead assertion(我不知道您的正则表达式库是否支持此功能)

      string pattern = "^city_date(?!.*metro)"
      

      我还在开头添加了一个锚点^,它将匹配字符串的开头。

      如果前面某处有字符串“metro”,则否定前瞻断言(?!.*metro) 将失败。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-12
        • 2013-09-23
        • 2020-05-01
        • 1970-01-01
        • 2019-10-07
        • 1970-01-01
        相关资源
        最近更新 更多