regular expression: if this is impossible, how to proceed ?
- From: Lion-O <nosp@xxxxxxxxxxxxxx>
- Date: Tue, 31 Jan 2006 21:38:57 -0000
Hi there,
I have a string which denotes a filename which optionally may have an
extension. Because I need to create an extra (supporting) file which will
contain basic certificates I decided to add (or change if its already there) an
extension .crt to denote the certificates.
After checking up on java.io and java.nio I found nothing to seperate an
extension so I decided to utilize regular expressions since I'm fairly familiar
with them on *nix. However, to my surprise the idea I had isn't working and I
can't think of anything else (not yet anyway) to solve this puzzle...
public void change_name() {
String filename = "filename.extension";
String regexp = "\..*$";
String new_ext = ".crt";
System.out.println( filename.replaceAll(regexp, new_ext));
}
When trying to compile this it will give you an error saying that the regexp.
is using an "illegal escape character". I can find a mention of this in the
documentation, the page about regexps. states (I quote:) "It is an error to use
a backslash prior to any alphabetic character that does not denote an escaped
construct; these are reserved for future extensions to the regular-expression
language.".
Well, this *does* denote an escape construct since I'm trying to grab a literal
.. after which the rest of the string follows untill the end of the line. Trying
to use other constructions like \Q and \E (literal / end literal) but those
give me an error as well.
I've managed to come up with an alternative but it isn't pretty :-(. Could
someone please point me to a more suitable solution or perhaps indicate
something obvious which I missed ?
Solution so far:
public void change_name() {
//String regexp = "\..*$";
int index = 0;
String filename = "filename.extension";
String new_ext = "crt";
StringBuffer new_name = new StringBuffer();
// Determine where the . is located
for (int i = filename.length() - 1; i > 0; i--) {
file (filename.charAt(i) == '.') { index = i; break; }
}
// Construct the filename without extension
for (int i = 0; i < (filename.length() - index - 1); i++) {
new_name.append(filename.charAt(i));
}
// Add the new extension
new_name.append(new_extension);
System.out.println("Old filename: " + filename);
System.out.println("New filename: " + new_name);
}
Thanks in advance.
--
Groetjes, Peter
..\\ PGP/GPG key: http://www.catslair.org/pubkey.asc
.
- Prev by Date: Re: Program will add but cannot get it to multiply
- Next by Date: Re: Program will add but cannot get it to multiply
- Previous by thread: Installation Woes (Windows)
- Index(es):
Relevant Pages
|