removing whitespaces from a QRegExpValidator - qt

I have a code someone wrote and there
this->llBankCode = new widgetLineEditWithLabel(tr("Bankleitzahl"), "", Qt::AlignTop, this);
QRegExpValidator *validatorBLZ = new QRegExpValidator(this);
validatorBLZ->setRegExp(QRegExp( "[0-9]*", Qt::CaseSensitive));
this->llBankCode->lineEdit->setValidator(validatorBLZ);
as it can be seen from this code, is that validatorBLZ can accept only numbers between 0 and 9. I would like to change it, that validatorBLZ would be able to get as an input whitespace as well (but not to start with a whitespace), but it wont be shown.
Example:
if i try to copy & paste a string of the format '22 34 44', the result would be an empty field. What i would like to happen is that the string '22 34 44' will be shown in the field as '223444'.
How could i do it?

You could try using:
QString string = "22 34 44";
string.replace(QString(" "), QString(""));
That will replace any spaces with a non-space.

Write your own QValidator subclass and reimplement validate and fixup. Fixup does what you ask for: changes the input in a way that makes it intermediate/acceptable.
In your case, consider the following code-snippet for fixup:
fixup (QString &input) const
{
QString fixed;
fixed.reserve(input.size());
for (int i=0; i<input.size(); ++i)
if (input.at(i).isDigit()) fixed.append(input.at(i));
input = fixed;
}
(this is not tested)
The validate function will obviously look similar, returning QValidator::Invalid when it encounters a non-digit character and returning the according position in pos.
If your BLZ is limited to Germany, you could easily add the validation feature that it only returns QValidator::Acceptable when there are eight digits, and QValidator::Intermediate else.
Anyhow, writing an own QValidator, which often is very easy and straight forward, is the best (and most future-proof) solution most of the time. RegExes are great, but C++ clearly is the more powerful language here, which in addition results in a much more readable validator ;).

Related

How to remove double qoutes in Objective-C

Let me introduce myself.
My name is Vladimir, C++ programmer, I am from Serbia. two weeks ago I have started to learn objective-C and it was fine until tonight.
Problem:
I cant remove double quotes from my NSLog output.
NSLog(#"The best singers:%#", list.best);
Strings are joined with componentsJoinedByString:#" and "
I would like to get something like this:
The best singers: Mickey and John.
But I get this:
The best singers: ("Mickey", and "John").
I cant remove comma (,) and parentheses either.
I have tried with "replaceOccurencesOfString" but with no success. It can remove any character except qoute and comma.
Also I have used -(NSString *)description method to return string.
You are getting the raw output from your list (which I assume is an array). You will have to do your own formatting to get this to display in the format that you want. You can achieve this by building your string by iterating through your array. Note that this probably isn't the most efficient nor the most robust way to achieve this.
NSMutableString *finalString = [NSMutableString string];
BOOL first = YES;
for (NSString *nameString in list) {
if (first) {
[finalString appendString:nameString];
first = NO;
} else {
[finalString appendString:[NSString stringWithFormat:#" and %#", nameString]];
}
}

QRegExp: individual quantifiers can't be non-greedy, but what good alternatives then?

I'm trying to write code that appends ending _my_ending to the filename, and does not change file extension.
Examples of what I need to get:
"test.bmp" -> "test_my_ending.bmp"
"test.foo.bar.bmp" -> "test.foo.bar_my_ending.bmp"
"test" -> "test_my_ending"
I have some experience in PCRE, and that's trivial task using it. Because of the lack of experience in Qt, initially I wrote the following code:
QString new_string = old_string.replace(
QRegExp("^(.+?)(\\.[^.]+)?$"),
"\\1_my_ending\\2"
);
This code does not work (no match at all), and then I found in the docs that
Non-greedy matching cannot be applied to individual quantifiers, but can be applied to all the quantifiers in the pattern
As you see, in my regexp I tried to reduce greediness of the first quantifier + by adding ? after it. This isn't supported in QRegExp.
This is really disappointing for me, and so, I have to write the following ugly but working code:
//-- write regexp that matches only filenames with extension
QRegExp r = QRegExp("^(.+)(\\.[^.]+)$");
r.setMinimal(true);
QString new_string;
if (old_string.contains(r)){
//-- filename contains extension, so, insert ending just before it
new_string = old_string.replace(r, "\\1_my_ending\\2");
} else {
//-- filename does not contain extension, so, just append ending
new_string = old_string + time_add;
}
But is there some better solution? I like Qt, but some things that I see in it seem to be discouraging.
How about using QFileInfo? This is shorter than your 'ugly' code:
QFileInfo fi(old_string);
QString new_string = fi.completeBaseName() + "_my_ending"
+ (fi.suffix().isEmpty() ? "" : ".") + fi.suffix();

Replace string from character onwards

I've got a string like so
Jamie(123)
And I'm trying to just show Jamie without the brackets etc
All the names are different lengths so I was wondering if there was a simple way of replacing everything from the first bracket onwards?
Some others are displayed like this
Tom(Test(123))
Jack ((4u72))
I've got a simple replace of the bracket at the moment like this
mystring.Replace("(", "").Replace(")","")
Any help would be appreciated
Thanks
VB.NET
mystring.Substring(0, mystring.IndexOf("("C)).Trim()
C#
mystring.Substring(0, mystring.IndexOf('(')).Trim();
One logic; get the index of the ( and you can trim the later part from that position.
public static string Remove(string value)
{
int pos = value.IndexOf("(");
if (pos >= 0)
{
return value.Remove(pos, remove.Length);
}
return value;
}
aneal's will work. The alternative I generally use because it's a bit more flexible is .substring.
string newstring = oldstring.substring(0,oldstring.indexof("("));
If you aren't sure that oldstring will have a "(" you will have to do the test first just as aneal shows in their answer.
String.Remove(Int32) will do what you need:
Deletes all the characters from this string beginning at a
specified position and continuing through the last position.
You will also have to .Trim() as well given the data with padding:
mystring = mystring.Remove(mystring.IndexOf("("C))).Trim()

Convert unicode digits from english to devanagari

I was looking for some RegEx or any other method to convert digits 0-9 into ०-९ (devanagari script). I am using asp.net but could not find any method in globalization namespace which does this.
Any help is greatly appreciated.
Found similar post here!
My solution is bit different though as I know the source and destination culture. So I can hard-code the digits array.
string devYear = "";
string[] devD = { "०", "१", "२", "३", "४", "५", "६", "७", "८", "९" };
char[] digits = curYear.ToCharArray();
foreach (char ch in digits)
{
devYear += devD[int.Parse(ch.ToString())];
}
Another change is that I am iterating through the year digits instead of devD array. Saves few iterations as most numbers will be less than 10 digit. In my case, only four digits.
Hopefully will be useful for someone stuck up on similar lines.
Does each latin digit 0..9 map to exactly a devanagari digit (I do think so, if I understand Wikipedia correctly)=
If yes, how about the following:
public static string ConvertDigits( string s )
{
return s
.Replace("0", "०")
.Replace("1", "१")
.Replace("2", "२")
.Replace("3", "३")
.Replace("4", "४")
.Replace("5", "५")
.Replace("6", "६")
.Replace("7", "७")
.Replace("8", "८")
.Replace("9", "९");
}
For optimization, you could check for string.IsNullOrEmpty() before calling the string.Replace function.
In Addition (if this is suitable for a devanagari digit), call the string.Replace() function overload that takes chars as parameters rather than strings.

Formatting asp.net label when the value is sourced from a query string

Afternoon all.
A very simple one for you today from thicky Rich.
I have a label I want to display as a lovely number format i.e. {0:N0}
Now, this label text equates to a query string value.
How do I go about formatting a label's text from a query string value in one fell swoop?
I have tried this
lblTotalPurchQS.Text = String.Format("{0:N0}",Request.QueryString["totalpurchasequantity"].ToString());
but with little success.
Any ideas or pointers?
Don't use ToString on the incoming query string parameter, but convert it to an int first:
lblTotalPurchQS.Text = String.Format("{0:N0}", int.Parse(Request.QueryString["totalpurchasequantity"]));
Note:
The above is not safe code. First, the conversion may fail with a conversion exception. You should also be HTML escaping the output, in case of XSS.
This is better:
int totalPurchaseQuantity;
if(int.TryParse(Request.QueryString["totalpurchasequantity"], out totalPurchaseQuantity))
{
lblTotalPurchQS.Text = Server.HtmlEncode(String.Format("{0:N0}", totalPurchaseQuantity);
}

Resources