提取部分字符串并将其更改为粗体并将其添加到 TextView

Extract part of string and change it to bold and add it to TextView

我有一个字符串,其中包含一些句子,例如:

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore [et dolore magna aliquyam erat], sed diam voluptua. ?At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren

在本文中,我添加了两个方括号“[ ]”,它们应该定位到我想要以粗体显示的部分。

现在它想用这个正则表达式提取这些括号之间的部分:

(?<=\[).+?(?=\])

加粗:

SpannableStringBuilder str = new SpannableStringBuilder("regex here");
str.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

并将其添加到一个字符串中并在 TextView 中显示。

我有做这件事的功能,但我不知道如何组合它。

希望大家帮帮我

这里我给大家举了个小例子。这正是你想要的。

public class TestActivity extends AppCompatActivity {
    private Button button;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        button = findViewById(R.id.button_action);
        textView = findViewById(R.id.title);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore [et dolore magna aliquyam erat], sed diam voluptua. ?At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren";
                Pattern pattern = Pattern.compile("\[[\w ]+\]");
                Matcher matcher = pattern.matcher(text);
                while (matcher.find())
                    text = text.replace(matcher.group(), matcher.group().replace("[", "<b>").replace("]", "</b>"));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    textView.setText(Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT));
                } else {
                    textView.setText(Html.fromHtml(text));
                }
            }
        });
    }
}