can anyone explain to me how to identify using regexes any string that contains for example a single P character in it? Could yo also explain how this is evaluated too?
EDIT: What is the difference between [^P*] and [^P]*?
can anyone explain to me how to identify using regexes any string that contains for example a single P character in it? Could yo also explain how this is evaluated too?
EDIT: What is the difference between [^P*] and [^P]*?
A string containing a single P character is:
In a regular expression format, this is:
^[^P]*P[^P]*$
where:
^ matches the start of the string[^P]* matches any character other than a P, 0 or more timesP matches P[^P]* matches any character other than a P, 0 or more times$ matches the end of the stringThe difference between [^P*] and [^P]* is:
[^P*] matches any single character that is neither P nor *[^P]* matches zero or more characters that are not PThe placement of the * is of course important here. Inside [], the * doesn't have any special meaning. Outside [], the * means "match the previous thing zero or more times".
Pattern class - please, have at look at it first.David, I think my answer at one of your previous questions will help you out. As for how it is evaluated, I'm not sure what you mean, but you might want to check out the API documentation for the Pattern class.
The difference between [^P*] and [^P]* is:
assuming you really want to check for a single "P". here's a non regex approach.
for(int i = 0 ;i< string.length(); i++){
if ( string.charAt(i) == 'P' ){
count++;
}
}
if ( count == 1 ){
System.out.println("String contains a single P");
}
containS() in the for loop instead of charAt(), which i think is also valid.