I want to bold text in between of **. I have tried with following code but no success. It is creating whole text bold.
Original String : **Hi**, My Name is **XYZ** with **PQR**"
Want Output : Hi, My Name is XYZ with PQR
This is what I have tried.
private SpannableStringBuilder getText() {
String message = "**Hi**, My Name is **XYZ** with **PQR**";
Pattern p = Pattern.compile(".+.+(.*?).+.+");
Matcher matcher = p.matcher(message);
SpannableStringBuilder spannable = new SpannableStringBuilder(message);
StyleSpan span = new StyleSpan(Typeface.BOLD);
while (matcher.find()) {
spannable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spannable;
}
Your regex pattern is using the *
symbol without escaping it. Thus, it is treated as a quantifier and not a character to be matched. Fixing the expression should let the rest of your code work as intended. To test patterns, you can use sites like regex101.com
While I haven't tested this extensively, the following pattern is a basic one that fits your needs: (\*\*)(.*?)(\*\*)
This allows you to match the substrings "**Hi**", "**XYZ**" and "**PQR**". Your code currently bolds these in their entirety. What you probably want to do is remove the asterisks and insert the middle text in bold.
As per my pattern, your text should be available as the second matched group. So you can extract indices from that to apply the span, and remove all **
occurrences from it. There should be methods in both the String and regex classes that can be used for this.
Based on your exact needs, you'd have different constraints and edge cases, like what to do with "****" where the middle text is empty.