How to use regex in C++? [closed] - regex

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a string like below:
std::string myString = "This is string\r\nIKO\r\n. I don't exp\r\nO091\r\nect some characters.";
Now I want to get rid of the characters between \r\n including \r\n.
So the string must look like below:
std::string myString = "This is string. I don't expect some characters.";
I am not sure, how many \r\n's going to appear.
And I have no idea what characters are coming between \r\n.
How could I use regex in this string?

Personally, I'd do a simple loop with find. I don't see how using regular expressions helps much with this task. Something along these lines:
string final;
size_t cur = 0;
for (;;) {
size_t pos = myString.find("\r\n", cur);
final.append(myString, cur, pos - cur);
if (pos == string::npos) {
break;
}
pos = myString.find("\r\n", pos + 2);
if (pos == string::npos) {
// Odd number of delimiters; handle as needed.
break;
}
cur = pos + 2;
}

Regular expressions are "greedy" by default in most regex libaries.
Just make your regex say "\r\n.*\r\n" and you should be fine.
EDIT
Then split your input using the given regex. That should yield two strings you can combine into the desired result.

Related

How can I add letters in a sentence? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I've asked to write code that gets a char array(sentence), if the there is an 'i' in the sentence I need to add the letter 'b' the letter 'i' again like this example:
pig -> pibig
I tried to use string.h functions but I didn't succeed to make it right.
Use std::string in string header file, and std::string::insert whenever you need to insert a char in string:
std::string my_string = "my satringa";
for (size_t i = 0; i < my_string.length(); ++i)
{
if (my_string.at(i) == 'a')
{
my_string.insert(i + 1, "b");
}
}
std::clog << my_string << std::endl;
Output:
> my sabtringab
If you are forced to use C-style strings, don't worry do all of your operations on std::string and then take the underlying stored string with std::string::c_str() as a C-style string (and don't forget to take a copy).

How to match a string to regex based on a certain index? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am working on a small project of mine, and I need to match a string to a regex value, and the first character of the match needs to start exactly at a certain index.
I need to do this in C++, but can't find a method or function that seems like it would work on cplusplus.com.
Eg. if I put in the string Stack overflow into the pattern f.ow
and an index of 3, it should return false. But if I set the index to 10, it should return true and allow me to find out what actually matched (flow). And if I put in an index of 11, it should also return false.
Try this function, hope this will work for you
#include<iostream>
#include<regex>
#include<string.h>
using namespace std;
bool exactRegexMatch(string str,int index){
regex reg("f(.)ow");
return regex_match(str.substr(index), reg);
}
int main(){
if(exactRegexMatch("Stack Overflow",10)){
cout<<"True"<<endl;
}
else{
cout<<"False"<<endl;
}
}
How to match a string to regex based on a certain index?
Pass the substring starting from the index as the string argument, and add ^ to the beginning of the regex so that it only matches when the pattern starts from the beginning of the substring.
This uses the whole string by constructing the regex.
strRx = `"^[\\S\\s]{" + strOffset + "}(f.ow)";
// make a regex out of strRx
or, use iterators to jump to the location to start matching from
bool FindInString( std::string& sOut, std::string& sInSrc, int offset )
{
static std::regex Rx("(f.ow)");
sOut = "";
bool bRet = false;
std::smatch _M;
std::string::const_iterator _Mstart = sInSrc.begin() + offset;
std::string::const_iterator _Mend = sInSrc.end();
if ( regex_search( _Mstart, _Mend, _M, Rx ) )
{
// Check that it matched at exactly the _Mstart position
if ( _M[1].first == _Mstart )
{
sOut = std::string(_M[1].first, _M[1].second);
bRet = true;
}
}
return bRet;
}

C++ How to Extract Substring between two same symbols [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am new to c++ programming. I need some help,
I have string :
---- Input : "Name : $$ Enter Your Name2 $$"
I want to extract string between $$ symbols including symbols :
---- Output : "$$ Enter Your Name2 $$"
Please help me.
Regular Expression are very useful in this case.
C++11 has regex library.
#include <string>
#include <regex>
std::string parse_string(const std::string& str) {
static const std::string REGEX_STR = R"__(\$\$(\w|\W)*\$\$)__";
std::regex regex(REGEX_STR);
std::smatch regex_iterator;
if (std::regex_search(str, regex_iterator, regex)) {
return regex_iterator.str();
}
return std::string("");
}
The code can be improved but it should represent a good starting point. Specific case should be handled, for example: more $$*$$ in a string, etc...
Note:
R"__(\$\$(\w|\W)*\$\$)__"; is a raw string in order to make more readable the regex.
Just search the string for the delimiter:
std::string parse_string(const std::string& str, const std::string& delim) {
auto start = str.find(delim);
if (start == std::string::npos)
return "";
auto end = str.find(delim, start + delim.size());
if (end == std::string::npos)
return str.substr(start);
else
return str.substr(start, end - start + delim.size);
}

What is the most efficient C++ method to split a string based on a particular delimiter similar to split method in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
Improve this question
getline(cin,s);
istringstream iss(s);
do
{
string sub;
iss>>sub;
q.insert(sub);
}while(iss);
I used this technique when question wanted me to split on the basis of space so can anyone explain me how to split when there's a particular delimiter like ';' or ':'.
Someone told me about strtok function but i am not able to get it's usage so it would be nice if someone could help.
First, don't use strtok. Ever.
There's not really a function for this in the standard library.
I use something like:
std::vector<std::string>
split( std::string const& original, char separator )
{
std::vector<std::string> results;
std::string::const_iterator start = original.begin();
std::string::const_iterator end = original.end();
std::string::const_iterator next = std::find( start, end, separator );
while ( next != end ) {
results.push_back( std::string( start, next ) );
start = next + 1;
next = std::find( start, end, separator );
}
results.push_back( std::string( start, next ) );
return results;
}
I believe Boost has a number of such functions. (I implemented
most of mine long before there was Boost.)

Parse string and swap substrings [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I parse a string given by a user and swap all occurrences of the old substring with the new string. I have a function to work with but I am really uncertain when it comes to strings.
void spliceSwap( char* inputStr, const char* oldStr, const char* newStr )
The simplest solution is to use google (First link) here. Also be aware that in C++ we prefer std::string over const char *. Do not write your own std::string, use the built-in one. Your code seems to be more C than C++!
// Zammbi's variable names will help answer your question
// params find and replace cannot be NULL
void FindAndReplace( std::string& source, const char* find, const char* replace )
{
// ASSERT(find != NULL);
// ASSERT(replace != NULL);
size_t findLen = strlen(find);
size_t replaceLen = strlen(replace);
size_t pos = 0;
// search for the next occurrence of find within source
while ((pos = source.find(find, pos)) != std::string::npos)
{
// replace the found string with the replacement
source.replace( pos, findLen, replace );
// the next line keeps you from searching your replace string,
// so your could replace "hello" with "hello world"
// and not have it blow chunks.
pos += replaceLen;
}
}