RegEx to match strings that have only one C
I am looking for some tips on how I can take a string like:
KIGABCCA TQABCCAXT
GABCCASZYU GZTTABCCA MHNBABCCA CLZGABCA ABCCALZH
ABCCADQRNS VIZABCCA GABCCAG
UEKABCCA KBTOABCCA GABCCAMFFJ HABCCAISOJ OFJJABCCA HPABCCA
WBXRABCCA
ABCCAKH
VABCCAJX WBDOABCCA ABCCAWM GCABCA QHRABCCA
ABCCAMDDD WPABCCAD OGABCCA
TVABCCA JGLABCA
IUABCCA
and to return any entire string with only one C in it.
PLEASE NOTE: I AM NOT LOOKING FOR A SOLUTION!
Just some pointers or a description of the sort of constructs I should be looking at.
I have been labouring over it for ages, and have come close to hurting someone because of this. It is a homework question and I'm not looking to cheat, just some guidance.
I have read ext开发者_如何学编程ensively about Reg Ex and I understand them.
I'm not looking for a beginners guide.
You want to first put a word boundary at the start and end. Then match any character that isn't C or a word boundary 0 or more times, then a C, then again, any character that isn't a C or word boundary 0 or more times. So it'll match a C on it's own, or a C with any non-C characters either (or both) side of it.
The no-C or word boundary you could do in two ways... say "any character that isn't a C or word boundary" or you could say "I want A, B or anything from D-Z". Up to you.
Search for a pattern that has the following elements, in order:
- The beginning of the string or any whitespace.
- Zero or more non-whitespace non-C characters.
- A "C"
- Zero or more non-whitespace non-C characters.
- The end of the string or any whitespace.
you can create a count function. then pass each string to it. just an example
String string = "KIGABCCA"
public static boolean countChar(String string, char ch){
int count =0;
for(int i = 0; i<string.length();i++){
if(string.charAt(i) == ch ){
count++;
}
}
if ( count == 1){
return true;
}else {
return false;
}
}
精彩评论