删除所有方括号内的内容

huangapple go评论64阅读模式
英文:

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 = &quot;This is a [value1] string within some [image-nnnn] stuff between square  [image] brackets&quot;;
String output = input.replaceAll(&quot;\\s*\\[.*?\\]\\s*&quot;, &quot; &quot;).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.

huangapple
  • 本文由 发表于 2023年6月8日 18:05:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430748.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定