有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用java查找带有正则表达式的子字符串

我需要在“你好,叫我XXX”的句子中找到一个子串。这个句子可能很长,唯一能帮助我确定名字是什么的是,名字总是在fromat"call me"+space+name"+dot中。然而,这句话也可能看起来像hello, call me. call me xxx.

Call me John. ⇒ John

Call me Call me John. ⇒ prohibited - confusing

Call me. Call me John. ⇒ John

Call me  Call me John. ⇒ John

Call me Peter .Call me John. ⇒ John

Call me Peter. Call me John. ⇒ prohibited - more then one name...

名称可以是除\r\n\0和点之外的任何字符序列

如果有人能帮我定义正则表达式,我将不胜感激。 我花了两个多小时想弄明白,但没有成功


共 (3) 个答案

  1. # 1 楼答案

    像这样的事情: .*Call\ me\ (.[\w]+).?

    在:http://www.rubular.com/在线检查它是否满足您的所有要求

  2. # 2 楼答案

    假设名称不能包含空格:

    String string = "Call me Peter .Call me John.";
    Matcher matcher = Pattern.compile ("Call me ([^\r\n\0\\. ]+)\\.").matcher (string);
    if (matcher.find ())
    {
        String name = matcher.group (1);
        if (matcher.find ()) throw new Exception ("Prohibited: too many matches!");
        System.out.println (name);
    }
    else throw new Exception ("Prohibited: no matches!");
    
  3. # 3 楼答案

    正则表达式应该适用于您:

    "(?<=call me )[^.]*"