正则表达式忽略不以字母开头的标记

Regex ignore tokens that do not start with letter

我如何编写忽略任何不以字母开头的标记的正则表达式?它应该用于 java.

示例:it 's super cool --> 正则表达式应匹配:[it, super, cool] 并忽略 ['s].

您可以使用 (?<!\p{Punct})(\p{L}+),这表示字母前面没有标点符号。注意(?<!是用来指定一个negative look behind. Check the documentation of Pattern来了解更多的

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

public class Main {
    public static void main(String[] args) {
        String str = "it 's super cool";
        Pattern pattern = Pattern.compile("(?<!\p{Punct})(\p{L}+)");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

输出:

it
super
cool

替代正则表达式:

"(?:^|\s)([A-Za-z]+)"

上下文中的正则表达式:

public static void main(String[] args) {
    String input = "it 's super cool";

    Matcher matcher = Pattern.compile("(?:^|\s)([A-Za-z]+)").matcher(input);

    while (matcher.find()) {
        String result = matcher.group(1);
        System.out.println(result);
    }
}

输出:

it
super
cool

注意:要匹配任何语言(例如印地语、德语、中文、英语等)的字母字符、字母,请改用以下正则表达式:

"(?:^|\s)(\p{L}+)"

有关 Unicode 脚本、块、类别和二进制属性的 class、Pattern 和 classes 的更多信息,请参见 here