aspose file tools
The moose likes Java in General and the fly likes Regular expression replacing [ ] Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Regular expression replacing [ ]" Watch "Regular expression replacing [ ]" New topic
Author

Regular expression replacing [ ]

Jack Wootton
Greenhorn

Joined: Dec 29, 2004
Posts: 6
I want to write a function to process my own UBB code, so (ignore spaces)

[ I M G ] myImage.gif [ / I M G ]

Would change to the html for an image. However the regular expression for replacing square brackets seems not to have been thought about. Below is some quick code that outlines what i want to do and the problem. Shove it in a JSP page:

<%! String foo = "[img]"; %>
<%! String result = ""; %>
<%= foo %>
<%
result = foo.replaceAll("[img]","-");
%>
<%= result%>


And the output is

[---]

So it is not replacing the '[' and ']' . This I understand is because '[' and ']' are used in regular expressions. However one cannot escape them because an error is thrown:

illegal escape character

What to do?
[ December 29, 2004: Message edited by: Jack Wootton ]
Eric Pascarello
author
Rancher

Joined: Nov 08, 2001
Posts: 15357
    
    6
you try \[IMG\]
Jack Wootton
Greenhorn

Joined: Dec 29, 2004
Posts: 6
Still, illegal escape character
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
I think what you have to do is escape the \ chacter so the expression should be:

\\[IMG\\]

The reson for the illegal escape character is Java doesn't understand \[
Jack Wootton
Greenhorn

Joined: Dec 29, 2004
Posts: 6
It worked. Thank you.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 56177
    
  13

Not really JSP-related, so even though resolved I'm moving this along so it can be available for future reference in a more appropriate forum.


[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regular expression replacing [ ]
 
Similar Threads
PatternSyntaxException with * in regex
Regarding Regex !
StringTokenizer I want to pass a String and tokenize
Display each character on a new line
Replacing values in Strings