开发者

How do you write a regular expression that allows the special character DOT?

How do you write a regular expressio开发者_Go百科n that allows the character DOT(.) in a user name?

For example:

R. Robert
X. A. Pauline 


Escape the dot with a backslash: \.


[a-zA-Z. ]+ allows letters, dot, and space characters.

import java.util.regex.*;

public class Test {
  public static void main(String [] args) throws Exception {
    String RE = "[a-zA-Z. ]+";
    String name = args[0];
    Pattern pattern = Pattern.compile(RE);

    Matcher m = pattern.matcher(name);
    System.err.println("`" + RE + 
                       (m.matches()?"' matches `":"' does not match `") + 
                       name + "'");
  }
}

Running:

$ java Test "R. Robert"
`[a-zA-Z., ]+' matches `R. Robert'

$ java Test "R.-Robert"
`[a-zA-Z., ]+' does not match `R.-Robert'


to search for a dot in a regex you usually need to escape it as it is a special character.

use \. to escape.

You don't need to escape if it is part of a capture group:

[A-Za-z.] will search for letters and the '.' character.


Your question isn't very clear - for starters, regexes don't "allow" or "disallow" anything, they merely match (or don't match) text. It's the code that invokes the regex that will decide what to do (e.g. is the regex searching for partial matches of invalid characters, or specifying a match for an entire whitelist, etc.?).

Reading between the lines, if you're asking for how to include a literal . character in a regex, you need to escape it - which in (almost?) all regex engines means preceding it with a backslash.

For instance, the regex:

P\..R

means "a capital P, then a period (.), then any character, then a capital R", and would match

P.AR
P..R
P.$R

but not

PEAR
PA.R
P.
P\.AR

etc.


The character . is .

For example if you want to get letters and the dot:

[\w.]+

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜