java求一个简单的正则表达式:以@开头,中间可以是任意字符除了‘尀’,重复1到20遍,以空格或者@结束

2025-01-06 02:23:59
推荐回答(5个)
回答1:

//已修改!
//匹配@xxx,长度为1-20。

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

private static String regex = "@[^\\\\@ ]{1,20}";
private static Pattern pattern = Pattern.compile(regex);

public static void main(String[] args) throws Exception {
printNames(matcherNames("@aaaaa@cccccc"));;
printNames(matcherNames("@bbbb @dddddd"));
}

private static String[] matcherNames(String input) {
List list = new ArrayList();
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
list.add(matcher.group());
}
return list.toArray(new String[0]);
}

private static void printNames(String[] names) {
System.out.printf("共匹配到%s个用户:\n", names.length);
for (int i = 0; i < names.length; i++) {
System.out.printf("用户%s是:%s\n", i + 1, names[i]);
}
}
}

回答2:

^@[^\\@\s]{1,20}

验证如何?

回答3:

@cccccc @bbbbb

回答4:

/@a*/你试一下,不过那个重复1到20遍不知道你什么意思,是重复匹配还是重复输出啊

回答5:

很简单:@\w+\b