java 分组 正则_正则表达式在Java中分组

我不建议以这种方式扫描标识符(但我相信你不想过度工程),你可能会喜欢以下解决方案,一般来说扫描标识符更严格(但坦率地说,我不相信我也以最正确的方式扫描标识符。此外,它可以在单个字符串中扫描几个完全/部分限定的标识符,但它完全忽略不合格的标识符(例如,class不明确)。

package stackoverflow;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import static java.lang.System.out;

import static java.util.regex.Pattern.CASE_INSENSITIVE;

import static java.util.regex.Pattern.compile;

public final class Q11554180 {

private Q11554180() {

}

//

// (3) The same as item (1) however we're ------------------------------------------------+

// capturing the group to get the class |

// name only |

// (2) At least one package name is required ---------------------------------+ |

// (1) We're searching valid package names only -----------------+ | |

// and we do not need to capture it ?: | | |

// +----------------+--------------+|+-------------+-------------+

// | ||| |

private static final Pattern pattern = compile("(?:[\\p{Alpha}_][\\p{Alnum}_]*\\.)+([\\p{Alpha}_][\\p{Alnum}_]*)", CASE_INSENSITIVE);

private static void find(CharSequence s) {

final Matcher matcher = pattern.matcher(s);

while ( matcher.find() ) {

out.println(matcher.group(1));

}

}

public static void main(String[] args) {

find("class gqlMain.Node; class gqlMain.p1.NodeA");

find("class gqlMain.p1.p11.NodeB");

find("class gqlMain.p1.p11.p111.NodeC");

find(Q11554180.class.getCanonicalName());

}

}上面的代码将产生以下输出:

Node

NodeA

NodeB

NodeC

Q11554180

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值