replacing a pattern not surrounded by another pattern
2014-08-29++ replacing a pattern not surrounded by another pattern
I tried to do this with a regular expression, but this was difficult
Here's the methods I wrote (which I included in my useful tools class):
^some testing of this code can be found here:
"F:\kurt\storage\CIM Research Folder\DR\2013\9-24-13\Test replace pattern not surrounded by surrounding pattern method 9-24-13.xlsx"
/*
* * We only want there to be a match if there is an even number of surrounding_pattern after the pattern. If there is an odd number, than that means the pattern is within at a least two surround_pattern
*/
public String replacePatternNotSurroundedBySurroundingPattern(String original_string, String pattern, String replacement_pattern, String surrounding_pattern)
int shift = replacement_pattern.length()-pattern.length();
//first get all the positions of the pattern
ArrayList positions = findPositionOfString(original_string, pattern);
//we actually only want the even positions of the string since the odd positions are just where all of the instances of pattern end instead of begin
//this code is a little bit tricky and I had to draw it on paper to visualize how to do this
//"F:\kurt\storage\CIM Research Folder\DR\2013\9-24-13\remove odd numbered items from a list 20130924_092117.jpg"
positions = removeOddElementsFromArrayList(positions);
//now for each position create a substring from that position to the end of the string and count how many times the surrounding pattern occurs. If the surrounding pattern occurs an even number of times, then replace the pattern with the replacement pattern
for(int i=0; i<positions.size(); i++)
{
int current_position = Integer.valueOf(positions.get(i).toString()).intValue();
try
{
int end_of_string = original_string.length();
String substring = original_string.substring(current_position-1, original_string.length());
int number_of_surrounding_pattern_positions = getMatchesRegEx(substring, surrounding_pattern);
if(number_of_surrounding_pattern_positions%2==0)
{
substring = substring.replaceFirst(pattern, replacement_pattern);
original_string = original_string.substring(0, current_position-1) + substring;
//we just took away characters of size pattern and added characters of size replacement_pattern
positions = updateAllPositions(positions, shift, i+1);
}
catch(Exception e)
}
return original_string;
}
private ArrayList removeOddElementsFromArrayList(ArrayList list)
int number_of_iterations = (list.size()+1)/2;
for(int i=1; i<=number_of_iterations; i++)
{
try
{
list.remove(i);
catch(Exception e)
}
return list;
}
private ArrayList updateAllPositions(ArrayList list, int shift, int starting_index)
for(int j=starting_index; j<list.size(); j++)
{
list.set(j, Integer.valueOf(list.get(j).toString()).intValue()+shift);
return list;
}