kiwi
kiwi

Reputation: 51

How to match the following coordinates pattern using regex on C++?

I'd like to check if it match the following format:

(integer,integer), including the parenthesis and the commas. For example:for (3,4) would return true and for (6.4 would return false I tried with

string input;
regex check("(\\-|+)?[[:d:]]+,?(\\-|+)?[[:d:]]+");
cin >> input;
if (regex_match(input, check)) cout << "okay" << endl;
else cout << "error";

but I'm getting runtime error

Upvotes: 2

Views: 178

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627100

It seems you are looking for

regex check(R"(\([-+]?\d+,[-+]?\d+\))")

This defines a pattern like ^\([-+]?\d+,[-+]?\d+\)$ when used with std::regex_match that requires a full string match.

Details:

  • ^ - start of string (implicit in regex_match)
  • \( - a (
  • [-+]? - 1 or 0 + or - chars
  • \d+ - 1 or more digits
  • , - a comma
  • [-+]? - 1 or 0 + or - chars
  • \d+ - 1 or more digits
  • \) - a )
  • $ - end of string (implicit in regex_match)

C++ demo:

regex check(R"(\([-+]?\d+,[-+]?\d+\))");
string s1("(44,45)");
string s2("(44,45");
smatch match;
if (regex_match(s1, match, check)) {
        cout << s1 << ": Matched!" << endl; 
} else {
    cout << s1 << ": Not matched!" << endl; 
}
if (regex_match(s2, match, check)) {
        cout << s2 << ": Matched!" << endl;     
} else {
    cout << s2 << ": Not matched!" << endl; 
}

Output:

(44,45): Matched!
(44,45: Not matched!

Upvotes: 2

Luciano Barreto
Luciano Barreto

Reputation: 11

Try input this regex \(\d{1,},\d{1,}\)

Maybe it might works

Upvotes: 0

Related Questions