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

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);
}

Related

Checking the availability of a word within a phrase, in a given position [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 1 year ago.
Improve this question
Please let me know how can I check whether the first word of a given string is "echo" ,ignoring if any spaces before the word.
Example:
string hello = " echo hello hihi";
if(startwith(hello, "echo")
{
//some code here
}
Please help me if possible
string_view has a similar functionality. Just skip the white space and use that.
#include <string>
#include <string_view>
using std::string, std::string_view;
constexpr bool StartsWithSkipWs(string_view const str,
string_view const prefix) noexcept {
auto begin = str.find_first_not_of(" \t\n\f\r\v");
if (begin == string_view::npos) return false;
return str.substr(begin).starts_with(prefix);
}
int main() {
string hello = "echo hello hihi";
if (StartsWithSkipWs(hello, "echo"))
{
// ...
}
}
#include<iostream>
#include<boost/algorithm/string.hpp>
using namespace std;
int main(){
string hello = " echo hello hihi";
boost::trim_left(hello);
string subst=hello.substr(0,4);
if(subst=="echo"){
////some code here
}
}

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 string handling function to get substring [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.
Improve this question
I remenber a function in C or C++ that can do something like this:
string = "Hello my name is: 1234567 have a good day!"
function(string, "Hello my name is: %s have a good day!", substring)
and substring would be 1234567. What function is that?
In C, you can do that with sscanf(). Of course, there is no string datatype in C, though:
#include <stdio.h>
int main(void)
{
const char string[] = "Hello my name is: 1234567 have a good day!";
char substring[32];
if(sscanf(string, "Hello my name is: %31s have a good day!", substring) == 1)
{
printf("got '%s'\n", substring);
}
return 0;
}
sscanf is the function that you search.
It seems like you are trying to extract the number and not really so much the substring.
If your prefix string always begins with the format: "Hello my name is: " You can do:
const auto size = strlen("Hello my name is: ");
int substring = stoi(string.substr(size));
If you are unsure of your prefix, then I'd recommend a regex:
smatch m;
regex_search(string, m, regex(".*?(-?\\d+)"));
int substring = stoi(m[1]);
You may be looking for sscanf, but you probably want C++ regular expressions.
Start with a std::regex:
std::regex re( "Hello my name is: \b(\w+)\b have a good day!" );
Then put it into a function:
std::string get_name( std::string const& src ) {
static std::regex re( R"-(Hello my name is: (\w+) have a good day!)-" );
std::smatch results;
bool bworked = std::regex_match( src, results, re );
if (!bworked) return {};
// Assert(results.size() >= 2);
if (results.size() < 2) return {};
return results.str(1);
}
This gives you a lot more control than sscanf with only a bit more work.
live example
Going beyond regular expressions reaches full on parsing.
This solution uses C++11 features. Some compilers have <regex> headers that are basically stubs as well, so check compiler support.

Parsing strings in variable and store them to a new variable [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I need to parse the following, which is stored in a variable, and extract only Names. These names should be placed in a new variable (all together separated by dot (.)). Any ideas?
Name : Mike Anderson\n
Age : 43\n
Name : Andie Jameson\n
Age : 35\n
The expected output should be a variable with content: Mike Anderson.Andie Jameson
Thank you.
There will be many useful methods for your situation.
This code is just one of them. I used std::istringstream, string::find().
int main()
{
//Originally, each data is from your source.
//but, this is just sample.
std::istringstream input;
input.str("Name : Mike Anderson\nAge : 43\nName : Andie Jameson\nAge : 35\n");
//to find pattern
std::string name_pattern = "Name : ";
std::size_t found = std::string::npos;
for (std::string line; std::getline(input, line); ) {
found = line.find(name_pattern);
if (found!=std::string::npos)
{
//write on file for 'directory'
std::string only_name(line, found + name_pattern.length() );
std::cout << "\nName : " << only_name;
continue;
}
}
getchar();
}
This code will print below like,

How to use regex in C++? [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 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.