用于检测类/接口/ etc声明的Java Regular Expression [英] Java Regular Expression for detecting class/interface/etc declaration

查看:119
本文介绍了用于检测类/接口/ etc声明的Java Regular Expression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个检测新类的正则表达式,例如:

I'm trying to create a regular expression that detect a new class for example:

public interface IGame {

private class Game {

这是我到目前为止所得到的,但它没有检测到:

This is what I have so far but it isn't detecting :

(line.matches("(public|protected|private|static|\\s)"+"(class|interface|\\s)"+"(\\w+)"))

有人可以给我一些指示吗?

Can anyone give me some pointers please?

推荐答案

改变你的正则表达式,如下所示,以匹配两种类型的字符串格式。

Change your regex like below to match both type of string formats.

line.matches("(?:public|protected|private|static)\\s+(?:class|interface)\\s+\\w+\\s*\\{");

示例:

String s1 = "public interface IGame {";
String s2 = "private class Game {";
System.out.println(s1.matches("(?:public|protected|private|static)\\s+(?:class|interface)\\s+\\w+\\s*\\{"));
System.out.println(s2.matches("(?:public|protected|private|static)\\s+(?:class|interface)\\s+\\w+\\s*\\{"));

输出:

true
true

这篇关于用于检测类/接口/ etc声明的Java Regular Expression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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