📜  Java中的量词(1)

📅  最后修改于: 2023-12-03 14:42:59.405000             🧑  作者: Mango

Java中的量词

在正则表达式中,量词用于指定一个表达式可以匹配的字符或子表达式的数量。Java中支持以下常见的量词:

* 量词

* 量词表示前面的字符或子表达式可以出现0次或多次。例如,a* 匹配0个或多个a字符。

String str = "aaa";
boolean match = str.matches("a*"); // true
+ 量词

+ 量词表示前面的字符或子表达式可以出现1次或多次。例如,a+ 匹配1个或多个a字符。

String str = "aaa";
boolean match = str.matches("a+"); // true
? 量词

? 量词表示前面的字符或子表达式可以出现0次或1次。例如,a? 匹配0个或1个a字符。

String str = "a";
boolean match = str.matches("a?"); // true
{n} 量词

{n} 量词表示前面的字符或子表达式必须出现n次。例如,a{3} 匹配3个a字符。

String str = "aaa";
boolean match = str.matches("a{3}"); // true
{n,} 量词

{n,} 量词表示前面的字符或子表达式必须出现至少n次。例如,a{2,} 匹配至少2个a字符。

String str = "aaa";
boolean match = str.matches("a{2,}"); // true
{n,m} 量词

{n,m} 量词表示前面的字符或子表达式必须出现n到m次。例如,a{2,3} 匹配2个或3个a字符。

String str = "aaa";
boolean match = str.matches("a{2,3}"); // true

以上是Java中常见的量词,它们可以组合使用来匹配更复杂的模式。在编写正则表达式时,请确保对量词的使用确切明确,以免导致意外的匹配结果。