简体   繁体   中英

QRegularExpression count number of occurrences

I have a QString and I want to count 2 things in QString:

a) Number of special chars

b) Number of consecutive 2 chars

For first one I tried this:

QRegularExpression var1("[$&+,:;=?@#|'<>.^*()%!-]");
myString.count(var1);

Which I don't know how to also count backslash and slash chars and I'm not sure if this is the way to check for ALL special chars.

For second one I tried this:

QRegularExpression var2("([a-z\\d])\\1\\1");
myString.count(var2);

and also this:

QRegularExpression var2("([a-zA-Z0-9\\d])\\1\\1");
myString.count(var2);

Which doesn't work at all.

Please advice, I need number of consecutive chars and number of special chars in QString.

For first one. Please try this.

  QRegularExpression var1("[$&+,:;=?@#|'<>.^*()%!-/\\\\]");

You can count slash by just 1 slash like other char. To cound backslash char, You need 4 backslashs. In regular expression, you need to escape backslash char to match backslash char(\\\\). And in C++, you also need to escape those 2 backslashs. As a result, you need 4 backslashes.

For second one, you need just one \\\\1 to match consecutive 2 chars. \\\\1 means the same char of first matched group so your regex actually matches consecutive 3 chars.

  QRegularExpression var2("([a-z\\d])\\1");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM