Regex question

Hello. How do I modify this pattern so that regex_search would find ONLY "\w{4}"?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 int main()
{
	string s;
	getline(cin, s);
	regex pat(R"(\W\w{4}\W)");
	smatch m;

	while (regex_search(s, m, pat))
	{
		for (auto x : m) cout << x << endl;
		s = m.suffix().str();
	}
	system("Pause");
	return 0;
}
I'm assuming your R before the pattern stands for Raw? Otherwise you will need to escape your backslashes.
Yes. So?
So... Change the regex to what you want? Remove the \W sets around the regex search term you expect to search for? I'm afraid I'm not sure what library you're using, but generally if you want to search for something you should... search for it..
I want to find 4 letter words. And this must be the pattern for it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>

int main()
{
    // http://www.regular-expressions.info/wordboundaries.html
    const std::regex re( R"(\b\w{4}\b)" ) ;

    const std::string str = "want to find every four letter word. And this must be the pattern for that." ;

    // http://en.cppreference.com/w/cpp/regex/regex_token_iterator
    std::copy( std::sregex_token_iterator( str.begin(), str.end(), re ), std::sregex_token_iterator(),
               std::ostream_iterator<std::string>( std::cout, "\n" ) ) ;
}

http://coliru.stacked-crooked.com/a/6125bdbf462a7474
Thanks.
How can I create a pattern which checks if a string is populated with same digits?
Example: "5555", "333", etc.
 
regex more_digits(R"(\d*)");

To match previously matched text again, use a backreference.
http://www.regular-expressions.info/backref.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>

int main()
{
    const std::regex re( R"(\b(\d)\1*\b)" ) ;  // \1 is the backreference to (\d)

    const std::string str = "2222 aaa 123 bbb 5 55555555 66 cc 777 7773 37777 737777 333333333" ;

    std::copy( std::sregex_token_iterator( str.begin(), str.end(), re ), std::sregex_token_iterator(),
               std::ostream_iterator<std::string>( std::cout, "\n" ) ) ;
}

http://coliru.stacked-crooked.com/a/f4959c92031d28a3
Topic archived. No new replies allowed.