我正在尝试使用正则表达式匹配字符串中的某些文本。
问题是即使我有匹配也总是-1。
holder.textViewPublisher.setText(post.getPublisher());
Pattern tagMatcher = Pattern.compile("[#]+[A-Za-z0-9-_]+\\b");
int start = post.getPublisher().indexOf(tagMatcher.toString());
int end = start + tagMatcher.toString().length();
任何想法为什么开始总是-1?
答案 0 :(得分:1)
因为你错了。 String.indexOf()
没有使用正则表达式,它只是查找子字符串("[#]+[A-Za-z0-9-_]+\\b"
)。
代码应该是这样的:
Pattern tagMatcher = Pattern.compile("[#]+[A-Za-z0-9-_]+\\b");
Matcher m = tagMatcher.matcher(post.getPublisher());
if (m.find()) {
// matches
int start = m.start();
int end = m.end();
}
可以多次调用
答案 1 :(得分:1)
它返回-1,因为你正在寻找正则表达式模式本身的索引作为字符串而不是寻找匹配。您需要使用Matcher对象来查找匹配的实例。