简体   繁体   中英

java.util.regex

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:

  • a (possibly empty) string containing non-P characters
  • a P
  • a (possibly empty) string containing non-P characters

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 times
  • P matches P
  • [^P]* matches any character other than a P, 0 or more times
  • $ matches the end of the string

The 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 P

The 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".

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:

  • [^P*] means "one character that is not P and *"
  • [^P]* means "zero or more characters that are all not P"

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");
}

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