英文:
Remove all inside square brackets
问题
I'm trying to remove all inside square brackets from a string.
如果我有一个字符串,例如:
"This is a [value1] string within some [image-nnnn] stuff between square [image] brackets"
我想要得到这个结果:
"This is a string within some stuff between square brackets"
我可以使用正则表达式像这样查找和删除这些内容吗?
val pattern = Pattern.compile("\[(.*?)\]")
或者我需要手动查找和替换?
谢谢您提前的回答
EDIT:
上面的代码不起作用,因为当我执行时找不到任何匹配项:
patter.matcher("This is a [value1] string within some [image-nnnn] stuff between square [image] brackets").matches()
英文:
As a title I'm trying to remove all inside square brackets from a string.
If I've for example a string like:
"This is a [value1] string within some [image-nnnn] stuff between square [image] brackets"
I would achieve this result:
"This is a string within some stuff between square brackets"
Could be possible use regex like this to find and remove that stuff?
val pattern = Pattern.compile("\\[(.*?)\\]")
Or need I to find and replace manually?
Thanks in advance
EDIT:
The code above not working because not find any maches when I execute:
patter.matcher("This is a [value1] string within some [image-nnnn] stuff between square [image] brackets").matches()
答案1
得分: 2
你的正则表达式已经在正确的轨道上,但我会使用这个版本:
String input = "This is a [value1] string within some [image-nnnn] stuff between square [image] brackets";
String output = input.replaceAll("\\s*\\[.*?\\]\\s*", " ").trim();
System.out.println(output);
// This is a string within some stuff between square brackets
正则表达式模式\s\[.*?\]\s*
还匹配方括号术语两侧的任何空白,用单个空格替换。这正确地将句子的两半拼接在一起。然后我们使用trim
删除任何前导/尾随空格。
英文:
Your regex is on the right track, but I would use this version:
<!-- language: java -->
String input = "This is a [value1] string within some [image-nnnn] stuff between square [image] brackets";
String output = input.replaceAll("\\s*\\[.*?\\]\\s*", " ").trim();
System.out.println(output);
// This is a string within some stuff between square brackets
The regex pattern \s\[.*?\]\s*
also matches any whitespace on either side of the bracketed term, replacing by a single space. This correctly splices together the two halves of the sentence. Then we trim to remove any leading/trailing whitespace.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论