Skip to content

Instantly share code, notes, and snippets.

@westc
Last active November 2, 2023 14:36
Show Gist options
  • Save westc/2138f8f33344f1011f6905a1c4f733cd to your computer and use it in GitHub Desktop.
Save westc/2138f8f33344f1011f6905a1c4f733cd to your computer and use it in GitHub Desktop.
Makes it possible to easily loop through all of the instances of a pattern within a string and replace the matches with something different.
/**
* Author: Chris West
* Description:
* Makes it possible to easily loop through all of the instances of a pattern
* within a string and replace the matches with something different.
*/
public class PatternReplacer {
public Matcher matcher {get; private set;}
public String match {
get { return p_match; }
set {
Integer startIndex = matcher.start() + offset;
io = io.substring(0, startIndex)
+ value
+ io.substring(startIndex + p_match.length());
nextOffset += value.length() - p_match.length();
p_match = value;
}
}
private String p_match;
private String io;
private Integer offset;
private Integer nextOffset = 0;
public PatternReplacer(String strPattern, String strInput) {
this(Pattern.compile(strPattern), strInput);
}
public PatternReplacer(Pattern pat, String strInput) {
matcher = pat.matcher(strInput);
io = strInput;
}
public Boolean find() {
offset = nextOffset;
Boolean result = matcher.find();
if (result) {
p_match = matcher.group();
}
return result;
}
public override String toString() {
return io;
}
}
// Turn camel-casing into underscore casing.
PatternReplacer pr = new PatternReplacer('[A-Z]+', 'SpanishFirstName');
while (pr.find()) {
Matcher m = pr.matcher;
pr.match = (m.start() == 0 ? '' : '_') + m.group().toLowerCase();
}
System.debug(pr.toString());
// Number the whitespace groups.
PatternReplacer pr = new PatternReplacer('\\s+', 'Your Mac will sleep soon unless plugged into a power outlet.');
for (Integer n = 1; pr.find(); n++) {
Matcher m = pr.matcher;
pr.match = ' (' + n + ') ';
}
System.debug(pr);
// Reverse the casing of normal English letters.
PatternReplacer pr = new PatternReplacer('([A-Z]+)|[a-z]+', 'Where in the world is Carmen Sandiego?');
while (pr.find()) {
Matcher m = pr.matcher;
String g = m.group();
pr.match = (m.group(1) == null ? g.toUpperCase() : g.toLowerCase());
}
System.debug(pr.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment