简体   繁体   English

正则表达式使用? Java运算符

[英]Regex using the ? Operator in java

I have a sample string that I want to match: "a123456.java,a12344*javaaaaaaaaaaaaa" 我有一个要匹配的示例字符串: "a123456.java,a12344*javaaaaaaaaaaaaa"

I use the following regex pattern: Pattern p=Pattern.compile("a[0-9]+[.]?[a-zA-Z]+"); 我使用以下正则表达式模式: Pattern p=Pattern.compile("a[0-9]+[.]?[a-zA-Z]+");

Now the ? 现在 ? operator means 0 or more occurrences of "." 运算符表示出现0次或多次"." . Why is the string "a12344*javaaaaaaaaaaaaa" not picked up by this? 为什么字符串"a12344*javaaaaaaaaaaaaa"未被选中? Why is the * character not counted as a 0 occurrence? 为什么*字符不算作0?

If you mean that you expected the * to be picked up by the . 如果您的意思是您希望*被*拾取. because that means 'anything': 因为那意味着“任何东西”:

Inside the character class, the . 在角色类内部, . becomes a literal . 变成文字. , instead of the character meaning 'anything'. ,而不是表示“任何内容”的字符。

If you want to match anything, then use .? 如果您想匹配任何内容,请使用.? instead of [.]? 而不是[.]?


If you meant that * is not . 如果您的意思是*不是. , so is zero occurrences of . ,则零次出现. :

You are right, but in your regex, the . 您是对的,但在您的正则表达式中, . must be followed by a letter ( [a-zA-Z] ), and the * is obviously not a letter. 必须后面跟一个字母( [a-zA-Z] ),并且*显然不是字母。

To clarify, you have: 为了澄清,您有:

a -> "a"
[0-9]+ -> "12344"
[.]? -> ""
[a-zA-Z]+ -> Cannot match "*"

right regex: a[0-9]+.*[a-zA-Z]+ 正确的正则表达式: a[0-9]+.*[a-zA-Z]+

[.] mean symbol . [.]表示符号.

? mean 0 or 1 平均0或1

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

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