我是一名PHP开发人员,从我开始学习Java到现在才几个月。这里,我在PHP中有一个函数,用于从字符串中检索哈希标签。
{
preg_match_all('/(^|[^a-z0-9_])#([a-z0-9_]+)/i', $text, $matchedHashtags);
$hashtag = '';
if (!empty($matchedHashtags[0])) {
foreach ($matchedHashtags[0] as $match) {
$hashtag .= preg_replace("/[^a-z0-9]+/i", "", $match) . ',';
}
}
return rtrim($hashtag, ',');
}此函数返回一个新字符串,其中包含由逗号分隔的散列表。我的问题是,如何在java中实现这个精确的功能?致以问候。
发布于 2021-05-16 11:37:58
一种选择可能是使用单个模式,而不是第一次匹配,然后替换。
然后,您可以将结果串连在一个字符串中,或者将结果添加到列表中,并使用带有逗号的String.join。
\B#\w*[A-Za-z]\w*\B匹配在\b不匹配的位置#\w*[A-Za-z]\w*匹配#和至少一个字符and (如果您不想根据注释只匹配数字或下划线)例如
List<String> matches = new ArrayList<String>();
Matcher m = Pattern.compile("\\B#\\w*[A-Za-z]\\w*")
.matcher("#test @#$#test a#test,#2021, #__");
while (m.find()) {
matches.add(m.group());
}
System.out.println(String.join(",", matches));输出
#test1,#test2https://stackoverflow.com/questions/67556143
复制相似问题