I have a string/column something like this
String a = "000003023_AggregateStopLossLimit_W x3A 973911_2012-12-22.PDF";
I want to create a substring which doesn’t have the part ' x3A 973911' in it.
Whic means I want something like this,
000003023_AggregateStopLossLimit_W_2012-12-22.PDF
There is a list of such strings which will have different values but the format will be the same. I want the part of string to be removed which comes after the first space and ends at the next ‘_’.
This is what I have done already, this is working fine, but want to know if there is a better way of doing it.
String b = a.replaceAll(a.substring(a.indexOf(" "), a.indexOf("_",a.indexOf(" "))),"");
It would be even better if I can do this in db itself, which is oracle, instead of in java. Any idea to get this formatted string from the column directly using select?
One more requirement, I dont want to display the extension of the file.
So nothing after the ‘.’ should be displayed, which means something like this '000003023_AggregateStopLossLimit_W_2012-12-22'
I tried the following using the previous solution of APC
select regexp_replace ( your_string
, '([^[:space]]*) (.*)_(.*)....'
, '\1_\3') as new_string from your_table
This is working fine for now.
This should be removing last 4 characters and have the risk of not getting proper result if the extension is more or less than 3 or if the string is not truncated.
I’m looking for a more aesthetic way to do it.
Any chance?
To do it in the database:
Unfortunately Oracle doesn’t have any syntax to enforce laziness (non-greediness) in its regex implementation. That’s why my original ‘(.*) ‘ included the
x3A: it matched up to the last space with a following underscore. However, the negation syntax will isolate the string up to the first space.You can format the replacement string anyway you want. The easy way out is to do what I have done, and hardcode the underscore between the two matched patterns. Alternatively you could make it a search pattern in its own right and include it in the replacement string (although you’re more more likley to do that for more complicated searches).
Oracle introduced Regular Expressions in 10g; the functions are covered in the documentation. The regex implementation is POSIX compliant, so it lacks some of the functions you might have come across in say Perl. The Regex support is detailed in an appendix to the SQL ref.
As for tutorials, well I have a much-thumbed copy of the O’Reilly pocket book; I was given my copy at Open World 2003 but the ebook is reasonably priced. Buy it here. Anotgher good starting point is a series of threads by
cdon the OTN forum: start reading here.