简体   繁体   English

QRegularExpression计数出现次数

[英]QRegularExpression count number of occurrences

I have a QString and I want to count 2 things in QString: 我有一个QString,我想算一下QString中的2件事:

a) Number of special chars a)特殊字符数

b) Number of consecutive 2 chars b)连续2个字符的数量

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. 请指教,我需要连续字符数和QString中的特殊字符数。

For first one. 对于第一个。 Please try this. 请尝试这个。

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

You can count slash by just 1 slash like other char. 您可以像其他char一样仅将斜杠数减1。 To cound backslash char, You need 4 backslashs. 要加反斜杠字符,您需要4个反斜杠。 In regular expression, you need to escape backslash char to match backslash char(\\\\). 在正则表达式中,您需要转义反斜杠char以匹配反斜杠char(\\\\)。 And in C++, you also need to escape those 2 backslashs. 在C ++中,您还需要转义这两个反斜杠。 As a result, you need 4 backslashes. 因此,您需要4个反斜杠。

For second one, you need just one \\\\1 to match consecutive 2 chars. 对于第二个字符,只需一个\\\\ 1即可匹配连续的2个字符。 \\\\1 means the same char of first matched group so your regex actually matches consecutive 3 chars. \\\\ 1表示第一个匹配组的相同字符,因此您的正则表达式实际上匹配连续的3个字符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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