![](/img/trans.png)
[英]How to remove content inside curly braces{} along with the braces from a string in java?
[英]How to remove embedded braces in Java string?
我有一個Java字符串, 可以在一個更大的字符串中多次包含“ {
”和“ }
”對:
"My name is {name}. I am a {animal}. I like to {activity} whenever it rains."
我正在嘗試編寫將剝離這些對的所有實例的代碼:
"My name is . I am a . I like to whenever it rains."
這些對可以出現在字符串內的任何位置 ,並且可能根本不會發生。 顯然String#replaceAll(someRegex, "")
在這里是有序的,但我似乎無法使someRegex
正確:
// My best attempt.
String stripped = toStrip.replaceAll("{*}", "");
有任何想法嗎? 提前致謝。
要匹配{
,你需要逃避它。 因為它在正則表達式中有一些特殊的含義。 所以,你需要\\\\{
和\\\\}
。 或者您也可以將它們包含在角色類中。
然后為了匹配它們之間的任何東西,你可以使用.*
。 dot (.)
匹配任何字符。 *
是量詞,表示匹配0 or more
。
所以,你的正則表達式是: -
\\{.*?\\}
要么: -
[{].*?[}]
請注意,我在那里使用了一個不情願的量詞 - .*?
。 注意?
在末尾。 在這種情況下,它用於匹配直到第一個}
。 如果你使用.*
而不是.*?
,你的正則表達式將覆蓋從第一個{
到最后}
的完整字符串,並替換所有內容。
另外,一個特殊的正則表達式元字符,在character class
使用時沒有特殊含義 - 那個[]
東西。 這就是為什么,當你像這樣使用它時,你不需要逃避它們。 因此第二個正則表達式。
這看起來很簡單,不是嗎? 好的,現在是時候通過一些教程來了解有關Regular Expression
更多信息。 您可以從http://www.regular-expressions.info/tutorial.html開始
嘗試使用最簡單的正則表達式\\{\\w*\\}
,如下所示:
String s = "My name is {name}. I am a {animal}. I like to {activity} "+
"whenever it rains.";
System.out.println(s.replaceAll("\\{\\w*\\}", ""));
上面的正則表達式將{}中包含的單詞字符條紋化。 如果要包含某些特殊字符,請將它們與大括號內提到的\\w
一起包含在內。
replaceAll("\\\\{.*?\\\\}", "")
應該完成這項工作
String stripped = "My name is {name}. I am a {animal}. I like to {activity} whenever it rains.".replaceAll("\\{.*?\\}", "");
System.out.println(stripped);
打印My name is . I am a . I like to whenever it rains.
My name is . I am a . I like to whenever it rains.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.