-1

I need to extract a String between two {}. For example, .split(regex)

{Regex is difficult.}fadsfjkaslfdjsa{Humbug}asfasdfjaskdlfjlkaf 

should return an array with Regex is difficult. as the first entry and Humbug as the second.

How would I write a regex to do this in Java?

I have tried the answers below, but I want to use myString.split(regex). I probably should have been more specific in my answer.

Should I even be using .split() for this or is there another way?

4

2 回答 2

5
String regex = "\\{([^}]*)\\}"

\\{\\}逃逸{},分别。
([^}]*)捕获之后的{所有内容和所有字符,但不包括}.
\\}最后要求有一个}

或者,一个非贪婪的捕获术语有效,即(.*?);但是,我认为字符类对于初学者来说更容易理解。

编辑:
要提取内容,只需执行以下操作:

Matcher m = Pattern.compile("\\{([^}]*)\\}").matcher(myString);

while (m.find()) 
{
     myArrayList.add(m.group(1)); 
}
于 2013-11-10T19:58:18.757 回答
1

你不能用正则表达式处理嵌套结构(这会召唤恶魔),但如果它们只有 1 级,那么你可以将它们与
\{(.*?)\}

而且正则表达式并不难。

于 2013-11-10T19:59:24.090 回答