如何匹配重复模式?

Osc*_*Ryz 19 java regex

我想匹配:

some.name.separated.by.dots
Run Code Online (Sandbox Code Playgroud)

但我不知道怎么做.

我可以像这样匹配一个部分

 \w+\.
Run Code Online (Sandbox Code Playgroud)

怎么说"重复那个"

Bar*_*ers 24

请尝试以下方法:

\w+(\.\w+)+
Run Code Online (Sandbox Code Playgroud)

+( ... )告诉它匹配的是括号内一次或多次.

请注意,\w只匹配ASCII字符,因此一个单词café不匹配\w+,更不用说包含Unicode的单词/文本了.

编辑

之间的区别[...](...)[...]始终与单个字符匹配.它被称为"字符集"或"字符类".所以,[abc]没有匹配字符串"abc",但匹配的人物之一a,bc.

\w+[\.\w+]*同样匹配你的字符串的事实是因为[\.\w+]匹配一个.或一个字符\w,然后由*它重复零次或多次.但是,\w+[\.\w+]*为此还会匹配像aaaaa或的字符串aaa............

(...)是,如我已经提到的,简单地用于组字符(和可能的重复的那些基团).

有关字符集的更多信息:http://www.regular-expressions.info/charclass.html

有关群组的更多信息:http://www.regular-expressions.info/brackets.html

编辑二

这是Java中的一个示例(看到您主要发布Java答案):

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

public class Main {
    public static void main(String[] args) {
        String text = "some.text.here only but not Some other " + 
                "there some.name.separated.by.dots and.we are done!";
        Pattern p = Pattern.compile("\\w+(\\.\\w+)+");
        Matcher m = p.matcher(text);
        while(m.find()) {
            System.out.println(m.group());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这将产生:

some.text.here
some.name.separated.by.dots
and.we
Run Code Online (Sandbox Code Playgroud)

注意m.group(0)并且m.group()是等价的:意思是"整个匹配".