简体   繁体   English

Java正则表达式模式匹配

[英]Java Regular Expression Pattern Matching

I want to create a regular expression, in Java, that will match the following: 我想用Java创建一个正则表达式,该正则表达式将匹配以下内容:

*A*B * A * B

where A and B are ANY character except asterisk, and there can be any number of A characters and B characters. 其中A和B是除星号之外的任何字符,并且可以有任意数量的A字符和B字符。 A(s) is/are preceded by asterisk, and B(s) is/are preceded by asterisk. A(s)之前带有星号,B(s)之前带有星号。

Will the following work? 请问以下工作? Seems to work when I run it, but I want to be absolutely sure. 运行它时似乎可以正常工作,但是我想绝对确定。

Pattern.matches("\\A\\*([^\\*]{1,})\\*([^\\*]{1,})\\Z", someString)

It will work, however you can rewrite it as this (unquoted): 它将起作用,但是您可以将其重写为以下形式(未引用):

\A\*([^*]+)\*([^*]+)\Z
  • there is no need to quote the star in a character class; 无需在字符类中引用星号;
  • {1,} and + are the same quantifier (once or more). {1,}+是相同的量词(一次或多次)。

Note 1: you use .matches() which automatically anchors the regex at the beginning and end; 注意1:您使用.matches()会自动将正则表达式锚定在开头和结尾; you may therefore do without \\A and \\Z . 因此,您可能没有\\A\\Z

Note 2: I have retained the capturing groups -- do you actually need them? 注意2:我保留了捕获组-您是否真的需要它们?

Note 3: it is unclear whether you want the same character repeated between the stars; 注3:不清楚是否要在星星之间重复相同的字符; the example above assumes not. 上面的示例假设不是。 If you want the same, then use this: 如果您要相同,请使用以下命令:

\A\*(([^*])\2*)\*(([^*])\4*)\Z

如果我正确的话..它可以很简单

^\\*((?!\\*).)+\\*((?!\\*).)+

If you want a match on *AAA*BBB but not on *ABC*DEF use 如果要在*AAA*BBB上匹配但在*ABC*DEF上不匹配

^\*([a-zA-Z])\1*\*([a-zA-Z])\2*$

This won't match on this either 这也不会匹配

*A_$-123*B<>+-321

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

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