• Post Reply Bookmark Topic Watch Topic
  • New Topic

regular expression to Remove field inside [ ] brackets  RSS feed

 
sarah Marsh
Ranch Hand
Posts: 282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello:

How to use regular expression to Remove field inside [ ] brackets

For example: how to change the string from [abc] + def + [ABC]
to [] + def + []?

Thanks!
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's pretty straightforward. You can actually do it with a single replaceAll() method call. Just match the brackets and the stuff inside it, and replace it with brackets. Also, don't forget to escape the square brackets.

Henry
 
sarah Marsh
Ranch Hand
Posts: 282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But whatever inside [] is random. I don't know it ahead of time.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sarah Marsh:
But whatever inside [] is random. I don't know it ahead of time.


So?!? Regular expressions allows you to match random characters. BTW, are you looking for a particular type of hint? Cause it will depend on how much regex you already know.

Henry
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the information provided by class java.util.Pattern.

One hint: you will want the non-greedy operators, otherwise it will replace [abc] + def + [ABC] with [].
 
sarah Marsh
Ranch Hand
Posts: 282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Regular Expression \\[\w+\\]
Replacement \\[\\]
on [yya] + [b]
Why doesn't work?

I expected [] + [].

Thanks!
 
sarah Marsh
Ranch Hand
Posts: 282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it, should be
Regular Expression \[\w+\]
Replacement \[\]
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you use "\\[.+?\\]" as your regular expression you can remove everything inside the brackets, not just letters.

Please note the +? combination - the ? makes it non-greedy. See my previous post as to why this is necessary.
 
sarah Marsh
Ranch Hand
Posts: 282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot, Rob and Henry.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!