开发者

Counting letters in string regex

开发者 https://www.devze.com 2023-02-05 08:37 出处:网络
i have a regex that is half working to count all strings which开发者_开发问答 have odd numbers of X\'s.

i have a regex that is half working to count all strings which开发者_开发问答 have odd numbers of X's.

^[^X]*X(X{2}|[^X])*$

This works for nearly all cases:

X
XXX
XAA
AXXX
AAAX etc

but fails when typing something like:

XAXAXA

I need an extra clause that allows for strings which have alternating X's that is XAXA. Contiguous X patterns are already being mapped by X{2}*.


The following regex matches string consisting of an uneven number of X's:

^[^X]*(X[^X]*X[^X]*)*X[^X]*$

A quick break-down:

^          # the start of the input
[^X]*      # zero or more chars other than 'X'
(          # start group 1
  X[^X]*   #   an 'X' followed by zero or more chars other than 'X'
  X[^X]*   #   an 'X' followed by zero or more chars other than 'X'
)          # end  group 1
*          # repeat group 1 zero or more times
X          # an 'X'
[^X]*      # zero or more chars other than 'X'
$          # the end of the input

So, the repeated group 1 causes to match zero, or an even number of X's to be matched, and the single X after is, makes it uneven.


Non-Regex Example

This may be performance-hindering, but I am not sure if you are worried about that.

String str = "AXXXAXAXXX";
char[] cArray = str.toCharArray();
int count = 0;

for (char c : cArray)
{
    if (c == 'X')
        count++;
}

if (count % 2 != 0)
    //Odd


try this, working fine for me ^[^X]*((X[^X]*){2})*X[^X]*$

tested against

X - match
XXX - match
XAA - match
AXXX - match
AAAX - match
XAXAXA - match
XXAAAAAX - match
AAXX - NO match
AAXXXXXXAX - match
0

精彩评论

暂无评论...
验证码 换一张
取 消