开发者

Why is this regex not matching?

I can't find out why my regex does not match a line when using java's String.matches method - it does match using on online regex tester.

Here is the Java-Code:

line.trim().replaceAll(" +", " ").matches("(c开发者_运维技巧onst )?[a-zA-Z0-9\\*]*\\ [a-zA-Z0-9\\*]*[,|)]");

and the line that should be matched:

bool fLoad)   // somecomment

Does anybody have any ideas why this is so?


matches() means it should match completely, i.e. the whole string fits the RE. Your RE does not allow anything after the ')'. Try using find() instead matches().


Seems like you are attempting to match some sort of variable declaration in source code.

In your regex, you have this after the part that I imagine is meant to match "const (optionally) datatype":

"(const )?[a-zA-Z0-9\\*]*\\ "

Is the \\ prior to the space intentional? Do you mean to match a single \ ?


Java's String.match() doesn't work the way many other languages implement it: the whole input has to be matched, so add .* to each end of your regex:

line.trim().replaceAll(" +", " ").matches(".*(const )?[a-zA-Z0-9\\*]*\\ [a-zA-Z0-9\\*]*[,|)].*");

I tested this and your sample line returns true from matches()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜