がお手伝いしますクラスです。
public class Replacer {
private final CharSequence mSource;
private final CharSequence mReplacement;
private final Matcher mMatcher;
private int mAppendPosition;
private final boolean mIsSpannable;
public static CharSequence replace(CharSequence source, String regex,
CharSequence replacement) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(source);
return new Replacer(source, matcher, replacement).doReplace();
}
private Replacer(CharSequence source, Matcher matcher,
CharSequence replacement) {
mSource = source;
mReplacement = replacement;
mMatcher = matcher;
mAppendPosition = 0;
mIsSpannable = replacement instanceof Spannable;
}
private CharSequence doReplace() {
SpannableStringBuilder buffer = new SpannableStringBuilder();
while (mMatcher.find()) {
appendReplacement(buffer);
}
return appendTail(buffer);
}
private void appendReplacement(SpannableStringBuilder buffer) {
buffer.append(mSource.subSequence(mAppendPosition, mMatcher.start()));
CharSequence replacement = mIsSpannable
? copyCharSequenceWithSpans(mReplacement)
: mReplacement;
buffer.append(replacement);
mAppendPosition = mMatcher.end();
}
public SpannableStringBuilder appendTail(SpannableStringBuilder buffer) {
buffer.append(mSource.subSequence(mAppendPosition, mSource.length()));
return buffer;
}
// This is a weird way of copying spans, but I don't know any better way.
private CharSequence copyCharSequenceWithSpans(CharSequence string) {
Parcel parcel = Parcel.obtain();
try {
TextUtils.writeToParcel(string, parcel, 0);
parcel.setDataPosition(0);
return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel);
} finally {
parcel.recycle();
}
}
}
と使用方法の一例:
CharSequence modifiedText = Replacer.replace("ABC aaa AB ABC aa ad ABC", "ABC",
Html.fromHtml("<font color=\"red\">CBA</font>"));
textView.setText(modifiedText);
この方法は非常にいいです。しかし、もし私が文字列の中のいくつかの単語のためにそれを適用したいのですが? –
私のソリューションを編集して、ターゲット文字列のすべての出現を変更してください – NickT
ありがとうございます。非常に便利なコード –