使用Java使用正则表达式查找更大字符串的子字符串 [英] Using Java to find substring of a bigger string using Regular Expression

查看:33
本文介绍了使用Java使用正则表达式查找更大字符串的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的字符串:

If I have a string like this:

FOO[BAR]

我需要一种通用的方法来从字符串中取出BAR"字符串,这样无论方括号之间是什么字符串,它都能得到字符串.

I need a generic way to get the "BAR" string out of the string so that no matter what string is between the square brackets it would be able to get the string.

例如

FOO[DOG] = DOG
FOO[CAT] = CAT

推荐答案

您应该能够使用非贪婪量词,特别是 *?.您可能需要以下内容:

You should be able to use non-greedy quantifiers, specifically *?. You're going to probably want the following:

Pattern MY_PATTERN = Pattern.compile("\[(.*?)\]");

这将为您提供一个模式,该模式将匹配您的字符串并将文本放在第一组的方括号内.查看模式API文档 了解更多信息.

This will give you a pattern that will match your string and put the text within the square brackets in the first group. Have a look at the Pattern API Documentation for more information.

要提取字符串,您可以使用以下内容:

To extract the string, you could use something like the following:

Matcher m = MY_PATTERN.matcher("FOO[BAR]");
while (m.find()) {
    String s = m.group(1);
    // s now contains "BAR"
}

这篇关于使用Java使用正则表达式查找更大字符串的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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