简体   繁体   English

java.util.regex中

[英]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? 任何人都可以向我解释如何使用正则表达式识别包含例如单个P字符的任何字符串? Could yo also explain how this is evaluated too? 你也可以解释一下它是如何评估的吗?

EDIT: What is the difference between [^P*] and [^P]* ? 编辑: [^P*][^P]*之间有什么区别?

A string containing a single P character is: 包含单个P字符的字符串是:

  • a (possibly empty) string containing non-P characters 包含非P字符的(可能为空)字符串
  • a P 一个P.
  • a (possibly empty) string containing non-P characters 包含非P字符的(可能为空)字符串

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]*匹配除P,0或更多次以外的任何字符
  • P matches P P匹配P.
  • [^P]* matches any character other than a P, 0 or more times [^P]*匹配除P,0或更多次以外的任何字符
  • $ matches the end of the string $匹配字符串的结尾

The difference between [^P*] and [^P]* is: [^P*][^P]*之间的差异是:

  • [^P*] matches any single character that is neither P nor * [^P*]匹配任何既不是P也不是*的单个字符
  • [^P]* matches zero or more characters that are not P [^P]*匹配零个或多个不是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. 至于它的评估方式,我不确定你的意思,但你可能想查看Pattern类的API文档。

The difference between [^P*] and [^P]* is: [^ P *]和[^ P] *之间的差异是:

  • [^P*] means "one character that is not P and *" [^ P *]表示“一个不是P和*的字符”
  • [^P]* means "zero or more characters that are all not P" [^ P] *表示“零个或多个字符都不是P”

assuming you really want to check for a single "P". 假设你真的想检查单个“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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM