How to use C++ regex to find characters between square brackets [duplicate] - c++

This question already has an answer here:
This regex doesn't work in c++
(1 answer)
Closed 2 years ago.
I have a C++ regex to search for characters inside square brackets, for instance if the string is x[7:0], I want to return 7:0. This is what my regex looks like -
std::regex reg("\[(.*?)\]");
When I compile (g++) I get the following warning -
../fixedPointFormatter.cc:30:18: warning: unknown escape sequence: ']'
std::regex reg("[(.*?)]");
^~~~~~~~~~~
The following returns nothing...
if (regex_search(arg, matches, reg)) {
for (int i=1; i<matches.size(); i++) {
cout << matches[i] << endl;
}
}
Can someone help identify what is wrong with this?

The regex needs the [ and the ] to be escaped using \. However, to provide that to the regex, you need to escape the \s in the string.
std::regex reg("\\[(.*?)\\]");

Related

C++ RegEx for this pattern [duplicate]

This question already has answers here:
Regex statement in C++ isn't working as expected [duplicate]
(3 answers)
Closed 3 years ago.
I want to be able to find this pattern inside a c++ string. The pattern is as follows:
FIXED_WORD ANY_WORD(...)
where FIXED_WORD refers to a fixed keyword and ANY_WORD can be any word as long as a bracket follows from it.
I have tried using RegEx such as keyword \b(.*)\b\((.\*)\), where I tried to use the word boundary \b(.*)\b to extract out ANY_WORD followed by a bracket:
std::string s = "abcdefg KEYWORD hello(123456)";
std::smatch match;
std::regex pattern("KEYWORD \b(.*)\b\((.*)\)");
if (std::regex_search(s, match, pattern))
{
std::cout << "Match\n";
for (auto m : match)
std::cout << m << '\n';
}
else {
std::cout << "No match\n";
}
I am always getting a no match for this.
You're forgetting that slashes are escaped when you use a string literal. Use a raw string e.g. R"(...)" to preserve the slashes
std::regex pattern(R"(KEYWORD \b(.*)\b\((.*)\))");
Then your pattern works as expected:
Match
KEYWORD hello(123456)
hello
123456
https://godbolt.org/z/dJaAAX

Regular expression to match input of n words separated by m spaces [duplicate]

This question already has answers here:
Regular expression capturing a repeated group
(1 answer)
c++ std::regex, smatch retains subexpressions only once for their apperance in a pattern string
(1 answer)
Closed 6 years ago.
So I'm learning regular expressions in c++11 and i'm trying to create a regular expression to match an input of N words separeted by M spaces.
So, for example, you input " word word word word ..." and you can continue like this for how long you like.
Now my problems come when I try to access the fields in the smatch variable after comparing an input to the regular expression. At the moment what I have is:
#include <regex>
regex input_reg(
"(?:[[:space:]]*"
"([[:alpha:]_]+)"
"[[:space:]]*)+");
smatch comparison;
if (regex_match(input, comparison, input_reg)){
for (smatch::size_type i = 0; i < comparison.size(); ++i){
cout << i << ": '" << comparison.str(i) << "'" << endl;
}
}
The problem with this is that for some reason, I get a match as I should but when I try to cout all the fields to see if it works I only get the initial match and the first field, nothing else:
0: ' word word word word '
1: 'word'
What am I doing wrong?
EDIT: The input is as seen in cout example of my code, it doesn't show all the spaces in the text for some reason.

How to match a string with an opening brace { in C++ regex

I have about writing regexes in C++. I have 2 regexes which work fine in java. But these throws an error namely
one of * + was not preceded by a valid regular expression C++
These regexes are as follows:
regex r1("^[\s]*{[\s]*\n"); //Space followed by '{' then followed by spaces and '\n'
regex r2("^[\s]*{[\s]*\/\/.*\n") // Space followed by '{' then by '//' and '\n'
Can someone help me how to fix this error or re-write these regex in C++?
See basic_regex reference:
By default, regex patterns follow the ECMAScript syntax.
ECMAScript syntax reference states:
characters:
\character
description: character
matches: the character character as it is, without interpreting its special meaning within a regex expression.
Any character can be escaped except those which form any of the special character sequences above.
Needed for: ^ $ \ . * + ? ( ) [ ] { } |
So, you need to escape { to get the code working:
std::string s("\r\n { \r\nSome text here");
regex r1(R"(^\s*\{\s*\n)");
regex r2(R"(^\s*\{\s*//.*\n)");
std::string newtext = std::regex_replace( s, r1, "" );
std::cout << newtext << std::endl;
See IDEONE demo
Also, note how the R"(pattern_here_with_single_escaping_backslashes)" raw string literal syntax simplifies a regex declaration.

Erase all occurences of a word from a string [duplicate]

This question already has answers here:
Replace part of a string with another string
(17 answers)
Closed 7 years ago.
I have a string such as:
AAAbbbbbAAA
I'd like to remove all the occurances of a pattern AAA to get:
bbbbb
The pattern can occur anywhere in the string.
Given:
string yourstring("AAAbbbAAA");
string removestring("AAA");
You could simply run something like this multiple times on your string:
yourstring.erase(yourstring.find(removestring), removestring.length());
Of course you will have to check that string::find actually finds an occurence before using string::erase.
Here is the code. It's not very much efficient, but works well, and is a tiny code.
string h = "AAAbbbAAAB";
int pos = h.find("AAA");
while(pos!=-1)
{
h.replace(pos, 3, "");
pos = h.find("AAA");
}
cout << h << endl;
It only works if you know the pattern. If it doesn't what you want, maybe you're looking for a pattern matching algorithm, like KMP.

How to check if a string starts with ' " ' (double quotes)? [duplicate]

This question already has answers here:
Regex for quoted string with escaping quotes
(17 answers)
Closed 8 years ago.
Every time I write " my compiler assumes I am trying to write a String. Instead I want my method to tell me if the incoming string starts with a double quote ""
Ex:
String n;
if(n==n.startsWith(" " " ));
doesn't work
Any suggestions??
You have to escape double quotes in string!
If you do it like this: " " ", string ends on second quotation mark. If in Java, you code should be like:
String n;
if(n.startsWith("\""))
{
// execute if true
}
Since you are matching just first character, you don't need to use such sophisticated tool as regular expressions:
String n;
if (n.charAt(0)=="\"")
{
// execute if true
}
BUT. You should make sure if string is not empty. Just for safety:
String n;
if (n.getText()!=null
&& !n.getText().isEmpty()
&& n.charAt(0)=="\"")
{
// execute if true
}
PS: space is a character.
PSS: flagged as dublicate.