How to ignore the middle of a string in a regular expression

80 Views Asked by At

I have a command string in which the middle part should be ignored.

Example:

settings:volume:save

Using QRegularExpression, I need an expression that returns true as soon as the first part of the command contains "settings", and the last part contains "save". The part in the middle does not matter.

I tried the below, but it does not work:

command = "settings:volume:save";
QRegularExpression regex("(^settings\..*_save$)");
if (regex.match(command).hasMatch())
    //match code 
2

There are 2 best solutions below

0
magrif On

Maybe don't use regexp and do like:

const auto options = command.split(':');
if (options.size() == 3 && options.first() == "settings" && options.last() == "save")
{

}

If you are fan on regexp, use:

QRegularExpression regex("^settings(.*)save$");
0
A.R.M On

If you test the following:

QRegularExpression regex("(^settings\..*_save$)");

using:

qDebug()<<regex.pattern();

You will get this output:

"(^settings..*_save$)"
  • \. will be recognized as a literal dot (.).
  • _ will be recognized as a literal unederscore (_).

That regular expression will match strings that start with "settings.", followed by any characters (except for a newline), and ending with "_save".

It would match this for example:

settings.somestring_save

To get an expression that matches strings starting with "settings", followed by any characters (except for a newline), and ending with "save", you could use the following regular expression:

^settings.*save$

Here is how it works:

  • ^settings: insures the string starts with "settings".
  • .*: allows any characters except for a newline, repeated 0-n times.
  • save$: insures the string ends with "save".

Example:

QString command = "settings.SOMESTRING_save";
QString command1 = "settings:volume:save";
QString command2 = "settingsANOTERHString123......save";

QRegularExpression regex("^settings.*save$");

qDebug()<<regex.match(command);
qDebug()<<regex.match(command1);
qDebug()<<regex.match(command2);

This outputs:

QRegularExpressionMatch(Valid, has match: 0:(0, 24, "settings.SOMESTRING_save"))
QRegularExpressionMatch(Valid, has match: 0:(0, 20, "settings:volume:save"))
QRegularExpressionMatch(Valid, has match: 0:(0, 34, "settingsANOTERHString123......save"))

For more specific explanation, you can use online regex testing websites.