Easy substring with java

@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~


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)

Leave a Reply

Your email address will not be published.