代码之家  ›  专栏  ›  技术社区  ›  jaxb

Java正则表达式

  •  4
  • jaxb  · 技术社区  · 16 年前

    我对正则表达式不太熟悉。
    我需要以下常规异常的帮助:
    1.字符串以字母单词开头,然后后跟任何字母或数字。e、 g.Abc 1月20日至12月15日
    2.十进制数的字符串。e、 邮编:450122224.00

    3 回复  |  直到 16 年前
        1
  •  3
  •   aioobe    16 年前
    // 1. String start with alpha word and then followed by
    //    any aplha or number. e.g. Abc 20 Jan to 15 Dec
    
    // One or more alpha-characters, followed by a space,
    //     followed by some alpha-numeric character, followed by what ever
    Pattern p = Pattern.compile("\\p{Alpha}+ \\p{Alnum}.*");
    for (String s : new String[] {"Abc 20 Jan to 15 Dec", "hello world", "123 abc"})
        System.out.println(s + " matches: " + p.matcher(s).matches());
    
    // 2. String for a decimal number. e.g. 450,122,224.00
    p = Pattern.compile(
            "\\p{Digit}+(\\.\\p{Digit})?|" +  // w/o thousand seps.
            "\\p{Digit}{1,3}(,\\p{Digit}{3})*\\.\\p{Digit}+"); // w/ thousand seps.
    for (String s : new String[] { "450", "122", "224.00", "450,122,224.00", "0.0.3" })
        System.out.println(s + " matches: " + p.matcher(s).matches());
    
    
    // 3. Also to check if String contain any pattern like 'Page 2 of 20'
    
    // "Page" followed by one or more digits, followed by "of"
    // followed by one or more digits.
    p = Pattern.compile("Page \\p{Digit}+ of \\p{Digit}+");
    for (String s : new String[] {"Page 2 of 20", "Page 2 of X"})
        System.out.println(s + " matches: " + p.matcher(s).matches());
    

    输出:

    Abc 20 Jan to 15 Dec matches: true
    hello world matches: true
    123 abc matches: false
    450 matches: true
    122 matches: true
    224.00 matches: true
    450,122,224.00 matches: true
    0.0.3 matches: false
    Page 2 of 20 matches: true
    Page 2 of X matches: false
    
        2
  •  0
  •   sigint    16 年前

    1.) /[A-Z][a-z]*(\s([\d]+)|\s([A-Za-z]+))+/

    [A-Z][a-z]* 大写的

    \s([\d]+)

    \s([A-Za-z]+) 作为一个单词的前缀应该是一个空格

    2.) /(\d{1,3})(,(\d{3}))*(.(\d{2}))/

    (\d{1,3})

    (,(\d{3}))* 以逗号为前缀的0或更多三位数的数字

    (.(\d{2})) 是两位数的小数

    3.) /Page (\d+) of (\d+)/

    (\d+) 一个或多个数字

    写这个(或任何正则表达式)时,我喜欢使用 this tool

        3
  •  0
  •   Jens    16 年前

    我不知道你在这里是什么意思。开头是一个单词,后面是任意数量的单词和数字? 试试这个:

    ^[a-zA-Z]+(\s+([a-zA-Z]+|\d+))+
    

    只要一个十进制数就可以了

    \d+(\.\d+)?
    

    \d{1,3}(,\d{3})*(\.\d+)?
    

    使用

    Page \d+ of \d+