1

I need to filter strings based on two requirements

1) they must start with "city_date"

2) they should not have "metro" anywhere in the string.

This need to be done in just one check.

To start I know it should be like this but dont know hoe to eliminate strings with "metro"

string pattern = "city_date_"

Added: I need to use the regex for a SQL LIKE statement. hence i need it in a string.

AJ.
  • 2,561
  • 9
  • 46
  • 81
  • 6
    you don't need regular expressions for this.. – Michal Klouda Oct 23 '12 at 10:33
  • See [this old question](http://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word). – Some programmer dude Oct 23 '12 at 10:37
  • Care to tell what I need ? BTW I know I need a regex for my needs. – AJ. Oct 23 '12 at 10:37
  • 4
    This is all you need `if (s.substr(0, 9) == "city_date" && s.find("metro") == string::npos)`, Regexes would be overkill I think. The 'just one check' requirement is fatuous. – john Oct 23 '12 at 10:40
  • see [how to check string start in C++](http://stackoverflow.com/questions/8095088/how-to-check-string-start-in-c) and [Check if a string contains a string in C++](http://stackoverflow.com/questions/2340281/check-if-a-string-contains-a-string-in-c) – Michal Klouda Oct 23 '12 at 10:40
  • @john You should agree also on fact that using C++ to split string looks like even larger overkill, in C# you just do `str.split(...)` ;) – Lu4 Jul 30 '15 at 09:28

3 Answers3

4

Use a negative lookahead assertion (I don't know if this is supported in your regex lib)

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

I also added an anchor ^ at the start, that will match the start of the string.

The negative lookahead assertion (?!.*metro) will fail, if there is the string "metro" somewhere ahead.

stema
  • 90,351
  • 20
  • 107
  • 135
3

Regular expressions are usually far more expensive than direct comparisons. If direct comparisons can easily express the requirements, use them. This problem doesn't need the overhead of a regular expression. Just write the code:

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
}
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

by using 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