suki2.jpg

« Tip to stop identify theft | Main| windows Installer clean up »

easy substring with java

QuickImage Category None
@formula is a fab thing, and some features just cant be beat, one of my faves is its

@Middle( string ; startString ; endstring )

Java has the normal substring stuff, but this format is a bit of a pain (I personally hate the whole "get indexof" rigmarole to do it), but with a bit of help from regular expressions we can just use this

private String getMiddle (String inStr, String startToken, String endToken){
String Expression = ".+" + startToken + "(.+?)" + endToken + ".+";
inStr = " " + inStr + " "
return inStr.replaceAll( Expression, "$1");
}

so say we have this String

String longString = "GD=testing~BSZ=567~ST=1~UNID=357DHFDC4DA4AE802574F60006F249~"

Then

getMiddle( longstring , "BZ=" , "~") will give us "567"

handy eh?

N. B. If you want to search for any of the following characters [\^$.|?*+() you need to put \\ before each one (except for "\" which only needs 1) as they are special characters in regular expressions (yes i should just alter the function to handle them, ill do it later)
Bookmark and Share

Comments

Gravatar Image1 - nods, jakarta.commons is rather good (i have used it before), and always with Java someone has always done it before you and better, but this way I don't have to store another jar in my agent or grovel to the admin for another jar in the ext directory

Gravatar Image2 - Another idea, which I would prefer, is using the lang package from jakarta.commons. Its StringUtils class has a method
public static String substringBetween(String str,String open,
String close).
It is well documented with regard to the handling of nasty corner cases, that eat quite a bit of my time.
{ Link }

Post A Comment

:-D:-o:-p:-x:-(:-):-\:angry::cool::cry::emb::grin::huh::laugh::lips::rolleyes:;-)

Avalable for on site contract in

 

Hire Me

Directly:

Curriculum Vitae

As a member of:
ldc_badge.gif

Contact My Grubby Hide

Skype Linkin Main Me Twitter

Get LDC Tshirts

All profits go to the Children’s Cancer Association (CCA) in the US.

Social ASW Rating

Enter a URL: