Java.util.regex

can someone explain to me how to identify with the help of regular expressions any string containing, for example, one character P? Could you also explain how this is evaluated?

EDIT: What is the difference between [^P*]and [^P]*?

+3
source share
3 answers

A string containing one P character:

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

In regex format, this is:

^[^P]*P[^P]*$

Where:

  • ^ matches the beginning of a line
  • [^P]* matches any character other than P, 0 or more times
  • P corresponds to P
  • [^P]* matches any character other than P, 0 or more times
  • $ matches end of line

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

*, , . [] * . [] * " ".

+6

, , . , , , API Pattern .

[^ P *] [^ P] * :

  • [^ P *] " , P *"
  • [^ P] * " , P"
+2

, "P". .

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

Source: https://habr.com/ru/post/1786098/


All Articles