Regular expressions. Search for words without repeating numbers

Viewed 64

I need to write the code that will output words without repeating digits. By assignment, I have to use the char array. I decided to do this with regular expressions. At the moment I have this expression:

regex rx ("^(?!.*(.).*\1)[0-9]+$");

If you take each word of the string separately, then regex works, but if you write all the words in the string separated by a space, then regex does not work. How can i fix this?

Input file: 1234567890 987 787

The code must output at least 1234567890, because this is the first match, and it does not output anything

Full code:

int main() {

    regex rx ("^(?!.*(.).*\1)[0-9]+$");
    ifstream fin;
    fin.open("input.txt");
    int counter = 0;
    char ch;
    while (ch = fin.get() != EOF)
    {
        counter++;
    }
    cout << counter << "\n";
    fin.close();
    fin.open("input.txt");
    char *str = new char [counter];
    fin.getline(str, counter, '\0');
    fin.close();
    cmatch res;

    std::regex_search(str, res, rx);
        std::cout << res[0] << std::endl;


    return 0;
}    
1 Answers

You can use

\b(?!\d*(\d)\d*\1)\d+\b

See the regex demo. Details:

  • \b - a word boundary
  • (?!\d*(\d)\d*\1) - no repeating digits allowed in the number
  • \d+ - one or more digits
  • \b - a word boundary

See the online C++ demo:

#include <string>
#include <iostream>
#include <regex>
using namespace std;

int main() {
    std::regex r(R"(\b(?!\d*(\d)\d*\1)\d+\b)");
    char *str = "1234567890 987 787";

    for (cregex_iterator it(str, str + strlen(str), r); it != cregex_iterator{}; it++)
    {
        cout << (*it).str() << endl;
    }
    return 0;
}

The output will be 1234567890 and 987.

Related