Replace the whole string with a new text using a regular expression [closed] - regex

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 2 days ago.
This post was edited and submitted for review yesterday.
Improve this question
I want to replace a String data with a new one where I do not know what is inside the string as it may be empty, spaces, alphabets, numerics, special characters, mix, etc. It is simple as below
String randomString = "Some Old String"; // It will be any string or may be an empty string too
print("Old String ${randomString}"); // Output = Some Old String
randomString = "Some New String";
print("New String ${randomString}"); // Output = Some New String
But due to some limitations (no need to define here), I can't use the upper process. I would like to do this with only sub-functions like .replaceAll, .replaceRange, .replaceMap, .replaceFirst, .replaceFirstMap etc. For that, I tried following.
String randomString = ""; // It will be any string or maybe an empty string too
print("Old String ${randomString}"); // Output = ""
randomString.replaceAll(RegExp(r"/\W/g"),"Some New String");
print("New String ${randomString}"); // Output = "" (Showing Empty)
What should be the regex to select all and replace with alphabets, digits, special characters, spaces, empty, etc.?
I am currently using RegExp(r"/\W/g") so tell me the correct one for my need.
Live DEMO:
jdoodle.com/ia/DVm

You can achieve this by creating TextInputFormatter class and pass it to inputFormatters parameter in TextField, here's an example:
class ReplaceTextInputFormatter extends TextInputFormatter {
#override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
// TODO replace the [[oldValue] with [newValue] for your needs
return newValue;
}
}
TextField(
inputFormatters: [ReplaceTextInputFormatter()],
)
Edit after #Muhammad Hassan's comment about no need for widgets.
We can achieve this using replaceRange from 0 to the string length, for example:
randomString.replaceRange(0, s.length, 'replacement');

Related

JsonCpp: Treat strings as numbers [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 days ago.
This post was edited and submitted for review 2 days ago.
Improve this question
I have floating-point numbers stored as strings. During serialization to JSON, I want to convert those strings to numbers. For example, the strings a="1.001" and b="0.1" must be converted to numbers:
{
"a" : 1.001,
"b" : 0.1
}
The folloiwng code:
val["a"] = "1.001";
val["b"] = "0.1";
Json::StreamWriterBuilder builder;
auto json=Json::writeString(builder,val);
std::cout << json << std::endl;
produces:
{
"a" : "1.001",
"b" : "0.1"
}
which is not what I want because numbers as strings are rejected by the server.
The following code:
val["a"] = std::stod("1.001");
val["b"] = std::stod("0.1");
Json::StreamWriterBuilder builder;
auto json=Json::writeString(builder,val);
std::cout << json << std::endl;
produces:
{
"a" : 1.0009999999999999,
"b" : 0.10000000000000001
}
however, that is also not what I want because I lose precision.
UPDATE:
I've solved the problem by implementing a custom Json::Writer.
I used the existing implementation of Json::FastWriter::writeValue as a starting point and made changes to the way it processes string values:
case stringValue: {
auto str = value.asString();
if (isNumeric(str))
document_ += str;
else
document_ += valueToQuotedString(str.c_str());
break;
}
While my solution works, it is not ideal because all string fields that contain valid floating-point numbers are now serialized as numeric type, and the server rejects JSON string fields that are represented solely as floating-point numbers without quotation marks.
Can you suggest any other solutions? Perhaps I should consider using a different JSON library?

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

Modifying specific characters in text input (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 6 years ago.
Improve this question
I receive text with special characters (such as á) so I have to manually search and replace each one with code (in this case "á")
I would like to have code to search and replace such instances automatically after user input. Since I'm a noob, I'll show you the code I have so far - however meager it may be.
// Text fixer
#include <iostream>
#include <fstream>
#include <string>
int main(){
string input;
cout << "Input text";
cin >> input;
// this is where I'm at a loss. How should I manipulate the variable?
cout << input;
return 0;
}
Thank you!
An easy method is to use an array of substitution strings:
std::string replacement_text[???];
The idea is that you use the incoming character as the index into the array and extract the replacement text.
For example:
replacement_text[' '] = " ";
// ...
std::string new_string = replacement_text[input_character];
Another method is to use switch and case to convert the character.
Alternative techniques are a lookup table and std::map.
The lookup table could be an array of mapping structures:
struct Entry
{
char key;
std::string replacement_text;
}
Search the table using the key field to match the incoming character. Use the replacement_text to get the replacement text.

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.