Twitter Updates

Thursday 21 January 2010

Java String Search and Replace

Java by default by default only searches for regular expressions and replaces with strings. The method below allows String search and string replace.

Why is regular expression search an issue ? if search for [ex] it will match 'e' and 'x' but not '[ex]' if you have control over thestring you could excape the special characters with '\[ex\]' but if you are loading from a config file and you know it is plain text then it would be nice if there was a simple search and replace function example supplied below:
public String replaceString(String input, String find, String replace, boolean casesensitive){
String input_case_adjusted = input;
if (casesensitive == false) {
//For Case Insensitive searchs
//Lowercase everything (but replace in the original string)
input_case_adjusted = input.toLowerCase() ;
find = find.toLowerCase() ;
}

int startPosition = input_case_adjusted.indexOf(find);
String start = "";
String end = "";

if (startPosition >= 0) {
if (startPosition > 0) {
start = input.substring(0, startPosition);
}
end = input.substring(startPosition + find.length());

return start + replace + end;
} else {
return input;
}
}

No comments: