java支持if-then-else regexp构造(Perl构造)吗? [英] does java support if-then-else regexp constructs(Perl constructs)?
问题描述
我在尝试编译以下正则表达式时收到PatternSyntaxException:
I receive PatternSyntaxException when try to compile the following regex:
"bd".matches("(a)?b(?(1)c|d)")
这个正则表达式匹配bd和abc。它与bc不匹配。
this regex matches bd and abc. It does not match bc.
任何想法?谢谢。
好的我需要写正则表达式以匹配接下来的4个字符串:
ok i need to write regex to match next 4 strings:
*date date* date date1*date2
不匹配:
*date* date1*date2* *date1*date2 date** ...
但这应该通过单个匹配来完成,而不是几个。
but this should be done with single matching, not several.
请不要发布以下答案:
(date*date)|(*date)|(date*)|(date)
推荐答案
根据OP的编辑和样本添加新答案:
Adding a new answer based on the OP's edit and samples:
确定我需要编写正则表达式来匹配接下来的4个字符串:
*日期日期*日期date1 * date2
不匹配:
* date * date1 * date2 * * date1 * date2 date ** ...
如果我认为我理解你,你可以使用基于的正则表达式Alan Moore伪条件技巧。
If I think I understand you, you could use a regex based on Alan Moore pseudo conditional trick.
像这样的东西 ^(?:[*]()) ?日期(?:(?!\ 1)[*](?:日期)?|)$
可能会有效。
我认为'日期'是唯一的样本中的文本,样本中的每组非空格字符都是不同的文本行。
Something like this ^(?:[*]())?date(?:(?!\1)[*](?:date)?|)$
might work.
I am asuming 'date' is the only text in the samples, and each group of non-space characters in the samples are distinct lines of text.
在通过的文本中,只有一个表单需要伪条件。那是'日期*日期'。所以,我在下面包含了一个Perl示例(因为我没有Java编译器),为了清晰起见扩展了正则表达式。
In your text that passes, there is only one form that requires a pseudo conditional. That is 'date*date'. So, I've included a Perl sample below (since I don't have a Java compiler) that expands the regex for clarity.
use strict;
use warnings;
my @samps = qw(
*date
date*
date
date*date
*date*
date*date*
*date*date
date**
);
for my $str (@samps)
{
print "\n'$str'\n";
if ($str =~
/
^ # Begin of string
(?: # Expr grouping
[*]() # Asterisk found then DEFINE capture group 1 as empty string
)? # End expr group, optional, if asterisk NOT found, capture group 1 stays UNDEFined
date # 'data'
(?: # Expr grouping
(?!\1) # Pseudo conditional: If no asterisk (group 1 is UNDEF), then
[*](?:date)? # look for '*' folowed by optional 'data'
| # OR,
) # Asterisk or not, should be nothing here
$ # End of string
/x)
{
print "matched: '$str'\n";
}
}
输出:
'*date'
matched: '*date'
'date*'
matched: 'date*'
'date'
matched: 'date'
'date*date'
matched: 'date*date'
'*date*'
'date*date*'
'*date*date'
'date**'
这篇关于java支持if-then-else regexp构造(Perl构造)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!