问题
I am very new to regex and text manipulation so this might be trivial for many but it is turning out to be quite a nuisance for me.
I have a string like so:
*text* text text text *text*
where the text b/w the * denotes the text that has to be bold
So the desired output is
text text text text text
I am halfway there using the following code
val string = "*text* text text text *text*"
val pattern = Pattern.compile("\\*")
val matcher = pattern.matcher(string)
val spannableString = SpannableString(string)
var counter = 0
val indexes = IntArray(1)
while (matcher.find()) {
if(counter==0){
indexes[0]=matcher.start()
counter+=1
}else if(counter==1){
spannableString.setSpan(
StyleSpan(Typeface.BOLD),
indexes[0],matcher.start(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
counter+=1
}
if(counter==2){
counter=0
}
}
textView.text = spannableString
}
The output right now is
*text* text text text *text* (the *s are bold as well)
I want to remove the *'s
I intend to use
val spannableString = SpannableString(string.replace("*",""))
to remove the *'s but after that, I am not able to adjust the indexes that need to be passed on. How do I do it? or is there a better way? Any help is greatly appreciated
回答1:
I implemented what you wanted in JavaScript. It should be somewhat similar in the language you are using.
The regex explained:
- find an
*
- capture one or more non-
*
characters in between the asterisks([^*]+)
- find a second
*
- capture all matched
g
flag - replace the matches with the captured group
$1
(and the tags).
let string = '*text* text text text *text*';
string = string.replace(/\*([^*]+)\*/g, '<strong>$1</strong>');
document.getElementById('span').innerHTML = string;
<span id='span'></span>
PS: if you omit the strong
tags in the string it will just remove the *
.
回答2:
IMO you don't really need a regex to solve your problem (There's a famous saying "If you're trying to solve a problem with RegEx, now you have 2 problems", and I use RegExs frequently enough to both agree and disagree).
You can use the indexOf
method in String
in a loop (Java, Kotlin) to find the *
s, while constructing your end result in a SpannableStringBuilder:
- Keep a variable pointing to the start of the current span (or -1 if no open spans).
- In every iteration, you use
indexOf
starting from the last index found. - Every time you find an opening
*
you append the text from the last position to the current one to your builder. - Every time you find a closing
*
you append the text from the opening*
to the closer, and set it as a bold span. - If you don't find a
*
at an iteration you append everything from the last stop to the builder - If you reach the end of the string and have an open
*
that was never closed you know you have an error. You can either apply a bold span or not (orthrow
).
Hope this helps.
Also, please don't hijack other questions with links to yours.
来源:https://stackoverflow.com/questions/59947482/how-to-adjust-index-in-a-string-after-removing-some-characters