java正则表达式如何定量“? “工作? [英] How does java regex quantifier “? ” work?

查看:70
本文介绍了java正则表达式如何定量“? “工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.out.println(Pattern.matches("[amn]?", "a"));




此声明返回true。



但是





This statement returns true.

But

System.out.println(Pattern.matches("[amn]?", "amn"));







System.out.println(Pattern.matches("[amn]?", "adef"));





这些陈述返回false。



为什么?



我尝试了什么:



我对正则表达量词的理解?是这个。



正则表达式: X?

描述: X出现一次或者完全没有



所以语句[amn]? amn应该返回true,因为a,m,n出现一次。同样在[amn]? adef只出现一次而且m和n根本不会发生。



我哪里错了?



These statements returns false.

Why ?

What I have tried:

My understanding about regex quantifier "?" is this.

Regex: X?
Description: X occurs once or not at all

So the statement "[amn]?" "amn" should return true because a,m,n occurs once. And similarly in "[amn]?" "adef" a occurs only once and m and n do not occur at all.

Where am I going wrong ?

推荐答案

问题是?意思是:0或1重复前面的项目

这意味着它是可选的。

取整数正则表达式:

The problem is that "?" means just that: "0 or 1 repetition of the preceding item"
Which means it's optional.
Take the "integer number" regex:
^[+-]?\d+




说的是整个字符串由至少一个数字组成,可以在前面加上一个加号或者字母

所以匹配:


What that says is "the whole string consists of at least one digit, which may be preceded by a single plus or minus"
So it matches:

0
1
123456789
-1
+0

但它赢了; t匹配

But it won;t match

A
++0
+-999

你的正则表达式匹配a','m'或'n'中的零个或一个字符 - 这意味着它匹配任何东西!

如果写成

Your regex matches "zero or one character from 'a', 'm', or 'n'" - which means that it matches anything at all!
if it was written as

^[amn]?


那么它匹配

Then it would match

a
n
m

但不匹配

But wouldn't match

b
c
9
Hello!



获取 Expresso 的副本[ ^ ] - 它是免费的,它会检查并生成正则表达式。


Get a copy of Expresso[^] - it's free, and it examines and generates Regular expressions.


这篇关于java正则表达式如何定量“? “工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆