如何用正则从TextView1提取Android包名并显示到TextView2?
从AndroidManifest.xml文本中提取包名并显示到TextView的实现方案
嘿,很高兴再帮你搞定这个问题!我清楚你想要点击Button1后,从TextView1里的AndroidManifest格式内容中提取动态变化的包名,再把它显示到TextView2里,咱们直接上具体实现步骤:
一、合适的正则表达式选择
要匹配Manifest里的package属性值,咱们可以用这个正则:
package="([^"]+)"
简单解释下:
package=":精准匹配包名属性的开头部分([^"]+):这是一个捕获组,用来提取双引号之间的所有内容([^"]表示匹配除双引号外的任意字符,+表示至少匹配一次)":匹配属性值的结束双引号
二、Android代码实现(Java版本)
在你的Activity里,按下面的步骤写代码:
- 先获取控件的引用:
TextView textView1 = findViewById(R.id.textview1); TextView textView2 = findViewById(R.id.textview2); Button button1 = findViewById(R.id.button1);
- 给Button设置点击事件,在事件里完成提取和显示:
button1.setOnClickListener(v -> { // 获取TextView1里的Manifest文本 String manifestContent = textView1.getText().toString().trim(); if (manifestContent.isEmpty()) { textView2.setText("Manifest内容为空"); return; } // 初始化正则相关对象 Pattern pattern = Pattern.compile("package=\"([^\"]+)\""); Matcher matcher = pattern.matcher(manifestContent); // 查找匹配的内容 if (matcher.find()) { // 提取捕获组里的包名(索引1是第一个捕获组) String packageName = matcher.group(1); textView2.setText(packageName); } else { textView2.setText("未找到有效包名"); } });
三、Kotlin版本实现(如果你用Kotlin开发)
如果你的项目是Kotlin,代码会更简洁:
val textView1 = findViewById<TextView>(R.id.textview1) val textView2 = findViewById<TextView>(R.id.textview2) val button1 = findViewById<Button>(R.id.button1) button1.setOnClickListener { val manifestContent = textView1.text.toString().trim() if (manifestContent.isEmpty()) { textView2.text = "Manifest内容为空" return@setOnClickListener } val pattern = Regex("package=\"([^\"]+)\"") val matchResult = pattern.find(manifestContent) textView2.text = matchResult?.groupValues?.get(1) ?: "未找到有效包名" }
四、一些需要注意的小细节
- 要确保TextView1里的内容是完整的Manifest格式,至少包含
package属性 - 代码里做了空内容判断,避免空指针异常
- 如果Manifest里有多个
package属性(虽然正常情况不会有),这个正则会匹配第一个出现的包名,符合常规需求
这样就能完美实现你想要的功能啦!
内容的提问来源于stack exchange,提问作者Muhammad Asim
相关产品推荐
相关产品推荐

