2

I´m looking for a regular expression in C++11 which can match a substring in a string.

Something like: "It´s a dark night out there..." and I´m searching for ark

So if a substring is somewhere in a string this expression shall match. Furthermore i would like to have the option to say that this match should be case sensitive or not.

I´ve already tried this but it doesn´t seem to work...

string str = "It´s a dark night out there...";
regex ex ("ark"); 
if (regex_match (str,ex))
    cout << "Match found!";

Does anybody know something like that?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Xenogenesis
  • 390
  • 4
  • 23

1 Answers1

8

Use regex_search instead of regex_match. The latter tries to match the entire subject string, while the former allows to match substrings.

And here are the possible flags, one of which (the first) represents case-insensitive matching.

Martin Ender
  • 43,427
  • 11
  • 90
  • 130
  • Ok, thanks for your help I´ve corrected it to `regex ex ("ark");` and `if (regex_search (str,ex))` – Xenogenesis Nov 21 '12 at 18:22
  • @Xenogenesis why the `.*`? if you use `regex_search`, `ark` is enough. – Martin Ender Nov 21 '12 at 18:23
  • Sorry, i´m still confused that there is no need for a wildcard – Xenogenesis Nov 21 '12 at 18:25
  • @Xenogenesis `regex_search` tries the match starting at every single position in the subject string. that means, if **any** substring of your subject matches the supplied pattern, `regex_search` will find it. You can think of `regex_match` as the same, but it "secretly" surrounds your pattern with `^yourpatternhere$`. – Martin Ender Nov 21 '12 at 18:27