Java正则表达式

Java正则表达式

语法简介

详情请移步

测试代码

@org.junit.Test
public void testRegex() {
 
    //奇数列为用来测试的模式,偶数列是用来测试的字符串
    String [] TEST_DATA = new String[]{
            "zo*","zoooo",
            "zo*","zos",
            "do(es)?","does",
            "do(es)?","do",
            "do(es){1}","does",
            "do(es){1}","do",
            "o{2,}","oooooo",
            "oo{2,}","o",
            "(o+)(s+)", "ooooooos",
            "(o+?)(.*)", "oooo",
            "(o+?)(.*)", "oooo",
            ".*","asdf\r\n",
            "[\\s\\S]*","asdf\r\n",
            "(a)(b)(c)(d)","abc",
            "(a)(b)(c)(d)","abcd",
            "dustr(?:y|ies)","industries",
            "dustr(?:y|ies)","industry",
            "windows(?=95|98)","windows95",
            "windows(?=95|98)","windows8.1",
            "windows(?!95|98)","windows95",
            "windows(?!95|98)","windows10",
            "(?<=95|98)windows","95windows",
            "(?<=95|98)windows","10windows",
            "(?<!95|98)windows","95windows",
            "(?<!95|98)windows","10windows",
            "z|food","z",
            "z|food","zood",
            "z|food","food",
            "[z|f]ood","z",
            "[z|f]ood","zood",
            "[z|f]ood","food",
            "[z|food]","z",
            "[z|food]","zood",
            "[z|food]","food",
            "[abc]","abc",
            "[abc]","bca",
            "[abc]","cba",
            "[^abc]","abcd",
            "[a-z]","ABCe",
            "[^a-z]","abcA",
            "er\\b","i never do",
            "er\\b","verb",
            "er\\B","i never do",
            "er\\B","verb",
            "\\d+","123xx234",
            "\\d*","123xx234",
            "\\d*?","123xx234",
            "\\d{0,}","123xx234",
            "\\d{1,}","123xx234",
            "\\D+","123xx456",
            "\\D*","123xx456",
            "\\D*?","123xx456",
            "\\D{0,}","123xx456",
            "\\D{1,}","123xx456",
            "\\D+","xx456",
            "\\D*","xx456",
            "\\D*?","xx456",
            "\\D{0,}","xx456",
            "\\D{1,}","xx456",
            "\\f","ssss\f",
            "\\n","ssss\n",
            "\\r","dddd\r",
            "s\\ss","s sss",
            "s[\\f\\n\\r\\t\\v]s","s s",
            "s\\Ss","s ssds",
            "d[^\\f\\n\\r\\t\\v]d","d dsd",
            "\\w","!!wwwww",
            "[A-Za-z0-9_]","!!wwww",
            "\\W","www!!!",
            "[^A-Za-z0-9_]","www!!",
            "\\x41\\x42","cdABab",
            "\\x04&1\\x04&2","cdABab",
            "(.)\\1","asdffgh",
            "(.)\\1\\1\\1\\1","asdfffffgh",
            "(.)\\1(.)\\2(.)\\3","assddffg",
            "(.)\70","a\70",
            "(.)\70","a\56",
            "\111","\111",
            "\\u00A9","©",
            "\\<the\\>","the woman",
            "\\<the\\>","other",
            "(him|her)","himself",
            "(him|her)","them",
            "foo\\((\\d*),(\\d*),(\\d*)\\)","foo(1,7,2)",
            ".*","I am lisi",
            "(.+) am (.+)","I am lisi",
            "(.{1}) am (.{2})","I am lisi",
            "\\b\\w+(?=ing\\b)","singing dancing",
            "(?<=\\bre)\\w+\\b","reading a book"
    };
 
    int order = 0;
    for(int index = 0;index < TEST_DATA.length / 2;index ++){
        printAllGroupIfFound(++order,TEST_DATA[index * 2],TEST_DATA[index * 2 + 1]);
    }
}
 
 
private void printAllGroupIfFound(int order,String pattern, String testStr) {
    Matcher matcher = Pattern.compile(pattern).matcher(testStr);
    Matcher matcher1 = Pattern.compile(pattern).matcher(testStr);
    Matcher matcher2 = Pattern.compile(pattern).matcher(testStr);
 
    StringBuilder builder = new StringBuilder();
 
    builder.append(String.format("%3s)Pattern:[%25s],Test String:[%20s]", order,pattern, testStr));
 
    builder.append(String.format(",isMatches:[%10s],isFind:[%10s],", matcher.matches(),matcher1.find()));
 
    if (matcher2.find()) {
 
        builder.append(String.format("group():[%20s],",matcher2.group()));
 
        for (int index = 0; index <= matcher2.groupCount(); index++) {
            builder.append(String.format("%s:[%10s] ", index, matcher2.group(index)));
        }
    }
 
    System.out.println(builder.toString());
}
 
@org.junit.Test
public void testRegex1(){
    String s = "foo(2,10,7)";   //foo\((\d)+,(\d)+,(\d)+\)   foo($3,$1,$2)  在ide搜索替换输入框中分别输入这两个表达式,对字符串s进行替换
    System.out.println("foo(10,7,2)".replaceAll("foo\\(([^,]*),([^,]*),([^,)]*)\\)","foo($2,$1,$3)"));   // foo(7,10,2)
    System.out.println("我是张三".replaceAll("^(.)是(.{2})$","$2是$1"));    //张三是我
}
 
@org.junit.Test
public void testReset(){
    Matcher matcher = Pattern.compile("^\\d*\\w*$").matcher("22ww");
    System.out.println(matcher.matches());   // true
    System.out.println(matcher.find());    //false
    matcher.reset();
    System.out.println(matcher.find());    //true
    matcher.reset();
    System.out.println(matcher.matches());    //true
}

注意

  • matcher()函数的意思是是否匹配,这里的匹配是指整个字符串是否匹配,就是说模式相等,而find()函数的意思是是否能够找到匹配指定模式的字串,只要有字串匹配就行,就是说模式包含.
  • somePattern.matcher(someStr).matches()^somePattern$.matcher(someStr).find()是等价的
  • printAllGroupIfFound开头连续定义了三个Matcher,是因为Matcher对象的matches()find()两个方法都只能调用一次.当然了,你也可以用reset()函数进行重置,供下次计算
  • 调用groupCount(),group()或者group(int group)这几个函数之前,必须先调用find(),matcher()方法只是生成matcher对象并分配每一个group的start,end索引空间,不会进行真正的匹配计算

测试结果

1)Pattern:[                      zo*],Test String:[               zoooo],isMatches:[      true],isFind:[      true],group():[               zoooo],0:[     zoooo]
2)Pattern:[                      zo*],Test String:[                 zos],isMatches:[     false],isFind:[      true],group():[                  zo],0:[        zo]
3)Pattern:[                  do(es)?],Test String:[                does],isMatches:[      true],isFind:[      true],group():[                does],0:[      does] 1:[        es]
4)Pattern:[                  do(es)?],Test String:[                  do],isMatches:[      true],isFind:[      true],group():[                  do],0:[        do] 1:[      null]
5)Pattern:[                do(es){1}],Test String:[                does],isMatches:[      true],isFind:[      true],group():[                does],0:[      does] 1:[        es]
6)Pattern:[                do(es){1}],Test String:[                  do],isMatches:[     false],isFind:[     false],
7)Pattern:[                    o{2,}],Test String:[              oooooo],isMatches:[      true],isFind:[      true],group():[              oooooo],0:[    oooooo]
8)Pattern:[                   oo{2,}],Test String:[                   o],isMatches:[     false],isFind:[     false],
9)Pattern:[                 (o+)(s+)],Test String:[            ooooooos],isMatches:[      true],isFind:[      true],group():[            ooooooos],0:[  ooooooos] 1:[   ooooooo] 2:[         s]
10)Pattern:[                (o+?)(.*)],Test String:[                oooo],isMatches:[      true],isFind:[      true],group():[                oooo],0:[      oooo] 1:[         o] 2:[       ooo]
11)Pattern:[                (o+?)(.*)],Test String:[                oooo],isMatches:[      true],isFind:[      true],group():[                oooo],0:[      oooo] 1:[         o] 2:[       ooo]
12)Pattern:[                       .*],Test String:[              asdf
],isMatches:[     false],isFind:[      true],group():[                asdf],0:[      asdf]
13)Pattern:[                  [\s\S]*],Test String:[              asdf
],isMatches:[      true],isFind:[      true],group():[              asdf
],0:[    asdf
]
14)Pattern:[             (a)(b)(c)(d)],Test String:[                 abc],isMatches:[     false],isFind:[     false],
15)Pattern:[             (a)(b)(c)(d)],Test String:[                abcd],isMatches:[      true],isFind:[      true],group():[                abcd],0:[      abcd] 1:[         a] 2:[         b] 3:[         c] 4:[         d]
16)Pattern:[           dustr(?:y|ies)],Test String:[          industries],isMatches:[     false],isFind:[      true],group():[            dustries],0:[  dustries]
17)Pattern:[           dustr(?:y|ies)],Test String:[            industry],isMatches:[     false],isFind:[      true],group():[              dustry],0:[    dustry]
18)Pattern:[         windows(?=95|98)],Test String:[           windows95],isMatches:[     false],isFind:[      true],group():[             windows],0:[   windows]
19)Pattern:[         windows(?=95|98)],Test String:[          windows8.1],isMatches:[     false],isFind:[     false],
20)Pattern:[         windows(?!95|98)],Test String:[           windows95],isMatches:[     false],isFind:[     false],
21)Pattern:[         windows(?!95|98)],Test String:[           windows10],isMatches:[     false],isFind:[      true],group():[             windows],0:[   windows]
22)Pattern:[        (?<=95|98)windows],Test String:[           95windows],isMatches:[     false],isFind:[      true],group():[             windows],0:[   windows]
23)Pattern:[        (?<=95|98)windows],Test String:[           10windows],isMatches:[     false],isFind:[     false],
24)Pattern:[        (?<!95|98)windows],Test String:[           95windows],isMatches:[     false],isFind:[     false],
25)Pattern:[        (?<!95|98)windows],Test String:[           10windows],isMatches:[     false],isFind:[      true],group():[             windows],0:[   windows]
26)Pattern:[                   z|food],Test String:[                   z],isMatches:[      true],isFind:[      true],group():[                   z],0:[         z]
27)Pattern:[                   z|food],Test String:[                zood],isMatches:[     false],isFind:[      true],group():[                   z],0:[         z]
28)Pattern:[                   z|food],Test String:[                food],isMatches:[      true],isFind:[      true],group():[                food],0:[      food]
29)Pattern:[                 [z|f]ood],Test String:[                   z],isMatches:[     false],isFind:[     false],
30)Pattern:[                 [z|f]ood],Test String:[                zood],isMatches:[      true],isFind:[      true],group():[                zood],0:[      zood]
31)Pattern:[                 [z|f]ood],Test String:[                food],isMatches:[      true],isFind:[      true],group():[                food],0:[      food]
32)Pattern:[                 [z|food]],Test String:[                   z],isMatches:[      true],isFind:[      true],group():[                   z],0:[         z]
33)Pattern:[                 [z|food]],Test String:[                zood],isMatches:[     false],isFind:[      true],group():[                   z],0:[         z]
34)Pattern:[                 [z|food]],Test String:[                food],isMatches:[     false],isFind:[      true],group():[                   f],0:[         f]
35)Pattern:[                    [abc]],Test String:[                 abc],isMatches:[     false],isFind:[      true],group():[                   a],0:[         a]
36)Pattern:[                    [abc]],Test String:[                 bca],isMatches:[     false],isFind:[      true],group():[                   b],0:[         b]
37)Pattern:[                    [abc]],Test String:[                 cba],isMatches:[     false],isFind:[      true],group():[                   c],0:[         c]
38)Pattern:[                   [^abc]],Test String:[                abcd],isMatches:[     false],isFind:[      true],group():[                   d],0:[         d]
39)Pattern:[                    [a-z]],Test String:[                ABCe],isMatches:[     false],isFind:[      true],group():[                   e],0:[         e]
40)Pattern:[                   [^a-z]],Test String:[                abcA],isMatches:[     false],isFind:[      true],group():[                   A],0:[         A]
41)Pattern:[                     er\b],Test String:[          i never do],isMatches:[     false],isFind:[      true],group():[                  er],0:[        er]
42)Pattern:[                     er\b],Test String:[                verb],isMatches:[     false],isFind:[     false],
43)Pattern:[                     er\B],Test String:[          i never do],isMatches:[     false],isFind:[     false],
44)Pattern:[                     er\B],Test String:[                verb],isMatches:[     false],isFind:[      true],group():[                  er],0:[        er]
45)Pattern:[                      \d+],Test String:[            123xx234],isMatches:[     false],isFind:[      true],group():[                 123],0:[       123]
46)Pattern:[                      \d*],Test String:[            123xx234],isMatches:[     false],isFind:[      true],group():[                 123],0:[       123]
47)Pattern:[                     \d*?],Test String:[            123xx234],isMatches:[     false],isFind:[      true],group():[                    ],0:[          ]
48)Pattern:[                   \d{0,}],Test String:[            123xx234],isMatches:[     false],isFind:[      true],group():[                 123],0:[       123]
49)Pattern:[                   \d{1,}],Test String:[            123xx234],isMatches:[     false],isFind:[      true],group():[                 123],0:[       123]
50)Pattern:[                      \D+],Test String:[            123xx456],isMatches:[     false],isFind:[      true],group():[                  xx],0:[        xx]
51)Pattern:[                      \D*],Test String:[            123xx456],isMatches:[     false],isFind:[      true],group():[                    ],0:[          ]
52)Pattern:[                     \D*?],Test String:[            123xx456],isMatches:[     false],isFind:[      true],group():[                    ],0:[          ]
53)Pattern:[                   \D{0,}],Test String:[            123xx456],isMatches:[     false],isFind:[      true],group():[                    ],0:[          ]
54)Pattern:[                   \D{1,}],Test String:[            123xx456],isMatches:[     false],isFind:[      true],group():[                  xx],0:[        xx]
55)Pattern:[                      \D+],Test String:[               xx456],isMatches:[     false],isFind:[      true],group():[                  xx],0:[        xx]
56)Pattern:[                      \D*],Test String:[               xx456],isMatches:[     false],isFind:[      true],group():[                  xx],0:[        xx]
57)Pattern:[                     \D*?],Test String:[               xx456],isMatches:[     false],isFind:[      true],group():[                    ],0:[          ]
58)Pattern:[                   \D{0,}],Test String:[               xx456],isMatches:[     false],isFind:[      true],group():[                  xx],0:[        xx]
59)Pattern:[                   \D{1,}],Test String:[               xx456],isMatches:[     false],isFind:[      true],group():[                  xx],0:[        xx]
60)Pattern:[                       \f],Test String:[               ssss],isMatches:[     false],isFind:[      true],group():[                   ],0:[         ]
61)Pattern:[                       \n],Test String:[               ssss
],isMatches:[     false],isFind:[      true],group():[                   
],0:[         
]
]
63)Pattern:[                     s\ss],Test String:[               s sss],isMatches:[     false],isFind:[      true],group():[                 s s],0:[       s s]
64)Pattern:[           s[\f\n\r\t\v]s],Test String:[                 s s],isMatches:[     false],isFind:[     false],
65)Pattern:[                     s\Ss],Test String:[              s ssds],isMatches:[     false],isFind:[      true],group():[                 sds],0:[       sds]
66)Pattern:[          d[^\f\n\r\t\v]d],Test String:[               d dsd],isMatches:[     false],isFind:[      true],group():[                 d d],0:[       d d]
67)Pattern:[                       \w],Test String:[             !!wwwww],isMatches:[     false],isFind:[      true],group():[                   w],0:[         w]
68)Pattern:[             [A-Za-z0-9_]],Test String:[              !!wwww],isMatches:[     false],isFind:[      true],group():[                   w],0:[         w]
69)Pattern:[                       \W],Test String:[              www!!!],isMatches:[     false],isFind:[      true],group():[                   !],0:[         !]
70)Pattern:[            [^A-Za-z0-9_]],Test String:[               www!!],isMatches:[     false],isFind:[      true],group():[                   !],0:[         !]
71)Pattern:[                 \x41\x42],Test String:[              cdABab],isMatches:[     false],isFind:[      true],group():[                  AB],0:[        AB]
72)Pattern:[             \x04&1\x04&2],Test String:[              cdABab],isMatches:[     false],isFind:[     false],
73)Pattern:[                    (.)\1],Test String:[             asdffgh],isMatches:[     false],isFind:[      true],group():[                  ff],0:[        ff] 1:[         f]
74)Pattern:[              (.)\1\1\1\1],Test String:[          asdfffffgh],isMatches:[     false],isFind:[      true],group():[               fffff],0:[     fffff] 1:[         f]
75)Pattern:[          (.)\1(.)\2(.)\3],Test String:[            assddffg],isMatches:[     false],isFind:[      true],group():[              ssddff],0:[    ssddff] 1:[         s] 2:[         d] 3:[         f]
76)Pattern:[                     (.)8],Test String:[                  a8],isMatches:[      true],isFind:[      true],group():[                  a8],0:[        a8] 1:[         a]
77)Pattern:[                     (.)8],Test String:[                  a.],isMatches:[     false],isFind:[     false],
78)Pattern:[                        I],Test String:[                   I],isMatches:[      true],isFind:[      true],group():[                   I],0:[         I]
79)Pattern:[                   \u00A9],Test String:[                   ©],isMatches:[      true],isFind:[      true],group():[                   ©],0:[         ©]
80)Pattern:[                  \<the\>],Test String:[           the woman],isMatches:[     false],isFind:[     false],
81)Pattern:[                  \<the\>],Test String:[               other],isMatches:[     false],isFind:[     false],
82)Pattern:[                (him|her)],Test String:[             himself],isMatches:[     false],isFind:[      true],group():[                 him],0:[       him] 1:[       him]
83)Pattern:[                (him|her)],Test String:[                them],isMatches:[     false],isFind:[     false],
84)Pattern:[ foo\((\d*),(\d*),(\d*)\)],Test String:[          foo(1,7,2)],isMatches:[      true],isFind:[      true],group():[          foo(1,7,2)],0:[foo(1,7,2)] 1:[         1] 2:[         7] 3:[         2]
85)Pattern:[                       .\*],Test String:[           I am lisi],isMatches:[      true],isFind:[      true],group():[           I am lisi],0:[ I am lisi]
86)Pattern:[             (.+) am (.+)],Test String:[           I am lisi],isMatches:[      true],isFind:[      true],group():[           I am lisi],0:[ I am lisi] 1:[         I] 2:[      lisi]
87)Pattern:[         (.{1}) am (.{2})],Test String:[           I am lisi],isMatches:[     false],isFind:[      true],group():[             I am li],0:[   I am li] 1:[         I] 2:[        li]
88)Pattern:[           \b\w+(?=ing\b)],Test String:[     singing dancing],isMatches:[     false],isFind:[      true],group():[                sing],0:[      sing]
89)Pattern:[           (?<=\bre)\w+\b],Test String:[      reading a book],isMatches:[     false],isFind:[      true],group():[               ading],0:[     ading]

如何使用正则表达式

编程中使用正则表达式其实还是比较常见的,比如常用的校验以及字符串替换等。
下面将会展示两个小例子

校验以及字符串替换

在进行数值转换的时候通常需要对待转换的字符串进行处理。当然如果你不做任何处理,直接做一个转换,并在转换的代码块外面加上try catch来捕获NumberFormatException
也可以,不过依赖异常处理机制来做数据的转换并不推荐。下面会展示如何利用正则表达式来做数值转换的操作。

首先需要梳理一下需要处理的情况:

  • 输入null,""字符串,应该返回null
  • 输入"abcd"这种字符串应该返回null,毕竟无法转换。
  • 然后就是输入数值了,输入任意整数值"1"应该返回数值1,输入任意浮点数比如"1.23"应该返回1.23,如果输入"1.2.3"应该返回null因为无法进行转换。
  • 当然了这个函数肯定是需要支持负数的
  • 一点特殊处理,在实际的业务需求中,可能会出现"123.45元","100笔"等,这种字面值当作字符串处理是没有问题的,但是我们其实更希望可以把它
    也当成数值处理,那么就是说你当字符串使用我就是"123.45元",但是当你把我按照数值使用我就是123.45.
  • 约定,系统中任何数值出现的形式都是Number类型,计算的形式可以是number.intValue(),number.floatValue(),number.doubleValue(),不过通常都是按照number.doubleValue()的方式来计算。

不多说了,上代码

  • 数值转换代码
    public Number parseNumber(String strToParse){
        if(StringUtils.isEmpty(strToParse)){
            return null;
        }
     
        String INVALID_FLOAT_CHAR_REG = "[^1234567890\\.\\-\\+)]*";
     
        Pattern REG_PATTERN_FOR_NUMBER = Pattern.compile("^(-?\\d+)(\\.\\d*)?(" +
                "世纪|年|月|周|日|时|点|分|秒|毫秒|微秒|纳秒|" +
                "美元|元|万美元|美元" +
                "十|百|千|万|十万|百万|千万|亿|十亿|百亿|千亿|" +
                "次|位|人|人次|" +
                "串|事|册|丘|乘|下|丈|丝|两|" +
                "举|具|美|包|厘|刀|分|列|则|" +
                "剂|副|些|匝|队|陌|陔|部|出|" +
                "个|介|令|份|伙|件|任|倍|儋|" +
                "卖|亩|记|双|发|叠|节|茎|莛|" +
                "荮|落|蓬|蔸|巡|过|进|通|造|" +
                "遍|道|遭|对|尊|头|套|弓|引|" +
                "张|弯|开|庄|床|座|庹|帖|帧|" +
                "席|常|幅|幢|口|句|号|台|只|" +
                "吊|合|名|吨|和|味|响|骑|门|" +
                "间|阕|宗|客|家|彪|层|尾|届|" +
                "声|扎|打|扣|把|抛|批|抔|抱|" +
                "拨|担|拉|抬|拃|挂|挑|挺|捆|" +
                "掬|排|捧|掐|搭|提|握|摊|摞|" +
                "撇|撮|汪|泓|泡|注|浔|派|湾|" +
                "溜|滩|滴|级|纸|线|组|绞|统|" +
                "绺|综|缕|缗|场|块|坛|垛|堵|" +
                "堆|堂|塔|墩|回|团|围|圈|孔|" +
                "贴|点|煎|熟|车|轮|转|载|辆|" +
                "料|卷|截|户|房|所|扇|炉|炷|" +
                "觉|斤|笔|本|朵|杆|束|条|杯|" +
                "枚|枝|柄|栋|架|根|桄|梃|样|" +
                "株|桩|梭|桶|棵|榀|槽|犋|爿|" +
                "片|版|歇|手|拳|段|沓|班|文|" +
                "曲|替|股|肩|脬|腔|支|步|武|" +
                "瓣|秒|秩|钟|钱|铢|锊|铺|锤|" +
                "锭|锱|章|盆|盏|盘|眉|眼|石|" +
                "码|砣|碗|磴|票|罗|畈|番|窝|" +
                "联|缶|耦|粒|索|累|緉|般|艘|" +
                "竿|筥|筒|筹|管|篇|箱|簇|角|" +
                "重|身|躯|酲|起|趟|面|首|项|" +
                "领|顶|颗|顷|袭|群|袋)?$");
     
        //检测格式是否匹配上述正则表达式
        if(!REG_PATTERN_FOR_NUMBER.matcher(strToParse).matches()){
            return null;
        }
     
        //替换掉无效字符
        strToParse = strToParse.replaceAll(INVALID_FLOAT_CHAR_REG,"");
        if(StringUtils.isEmpty(strToParse)){
            return null;
        }
     
        //转换
        return Double.valueOf(strToParse);
    }
  • 测试代码
    @Test
    public void testREG1(){
        assertEquals(null,parseNumber(null));
        assertEquals(null,parseNumber(""));
     
        assertEquals(null,parseNumber("ss"));
        assertEquals(null,parseNumber("s1s"));
        assertEquals(null,parseNumber("1s"));
        assertEquals(null,parseNumber("1.2.3"));
        assertEquals(null,parseNumber("1.2.3元"));
        assertEquals(null,parseNumber(".2"));
     
        assertEquals(123.0,parseNumber("123."));
        assertEquals(123.0,parseNumber("123元"));
        assertEquals(123.45,parseNumber("123.45美元"));
        assertEquals(1.0,parseNumber("1笔"));
    }

    上面这些测试用例都会通过。当然这只是一个小例子。之后这个函数还可以不断优化来满足更多的场景。

如何把输入输出文档转换成字典类

在实际的业务开发过程中,输入输出一般都是Json,一般有产品提供需求文档,其中定义了输入输出的字典格式。
但是在实际开发过程中不推荐直接用jsonObj.put("xxx","xxx")这种方式构造输出,一般都会对输入输出的
key进行常量定义,使用的时候直接使用静态常量名称,之后有输出需求变更的时候直接更改常量字典类就可以了,
不需要在业务代码中一个个找。比如下面这种

  /**
   * 全部数据中21:00–6:00通话次数占通话总次数比
   */
  public static final String ALL_NIGHT_CALL_COUNT_RATIO = "all_night_call_count_ratio";  

怎么做呢,我们先看下输入是什么,输入一般来自与需求文档,像这种

  21:00-6:00通话次数占通话总次数比 string all_night_call_count_ratio
  近1月21:00–6:00通话次数占通话总次数比 string last_one_month_night_call_count_ratio
  近3月21:00–6:00通话次数占通话总次数比 stringlast_three_month_night_call_count_ratio

其实就是Excel里面的三列嘛,我们将其复制出来放到一个字符串中。

  String str = "21:00-6:00通话次数占通话总次数比\tstring\tall_night_call_count_ratio\n" +
            "近1月21:00–6:00通话次数占通话总次数比\tstring\tlast_one_month_night_call_count_ratio\n" +
            "近3月21:00–6:00通话次数占通话总次数比\tstring\tlast_three_month_night_call_count_ratio\n";

输出的样子输入的样子都已经明了了,接下来就是怎么进行转换了,你可以一个一个复制粘贴,一个一个改,不过怎么说呢,
如果程序员乐于做这种重复性劳动那就太让人尴尬了。我先直接上代码和结果,大家看下效果。

  • 转换代码
      System.out.println(str
              .replaceAll("(\\S+)(\\s+)(\\S+)(\\s+)(\\S+)","/**$1*/$5")   //1  /**21:00-6:00通话次数占通话总次数比*/all_night_call_count_ratio
              .replaceAll("(/\\*\\*\\S+\\*/)(\\w+)","$1$2 = \"$2\";")    //2    /**21:00-6:00通话次数占通话总次数比*/all_night_call_count_ratio = "all_night_call_count_ratio";
              .replaceAll("(\\w+ =)","public static final String $1"));    //3    public static final String last_three_month_night_call_count_ratio = "last_three_month_night_call_count_ratio";
  • 转换结果
      /**21:00-6:00通话次数占通话总次数比*/public static final String all_night_call_count_ratio = "all_night_call_count_ratio";
      /**近1月21:00–6:00通话次数占通话总次数比*/public static final String last_one_month_night_call_count_ratio = "last_one_month_night_call_count_ratio";
      /**近3月21:00–6:00通话次数占通话总次数比*/public static final String last_three_month_night_call_count_ratio = "last_three_month_night_call_count_ratio";
  • 怎么样是不是很舒服,代码已经写好了,只需要从Console中粘出来放到java类里面就好了,当然了,还是要做一些调整的,
    比如首先你需要进行一下代码格式化(ctrl + shit + f),然后将变量名全部大写(鼠标移到变量名称上面,ctrl + shift + x),
    至此这部分代码就写好了。之后有其他模块只需要把excel里面定义的字典粘到字符串str中,跑一下代码就好了。

当然为了将你定义的Key输出到一个Json字典中还可以加上下面这一块代码,输入都是一样的。

  • 转换代码
      System.out.println(str
          .replaceAll("string|jsonarray|json|boolean","")    //4   替换掉string|jsonarray|json|boolean
          .replaceAll("([^\\s]+)\\s+([^\\s]+)","-$2,\"$1+")    //5    前后两个部分调换顺序
          .replaceAll("-","dictJsonObj.put(")    //6    前面加上dictJsonObj.put(
          .replaceAll("\\+","\");"));    //7   后面加上 );
  • 转换结果
      dictJsonObj.put(all_night_call_count_ratio,"21:00dictJsonObj.put(6:00通话次数占通话总次数比");
      dictJsonObj.put(last_one_month_night_call_count_ratio,"近1月21:00–6:00通话次数占通话总次数比");
      dictJsonObj.put(last_three_month_night_call_count_ratio,"近3月21:00–6:00通话次数占通话总次数比");
  • 大概解释一下上面每行转换代码的意思
    • 1:我们看每行输入的格式,非空白字符的描述+一个空格或者tab+一个描述当前字段的类型的字符串比如string+一个空格或者tab+当前字段key的名称,好了格式很清晰了
      我们用的是(\\S+)(\\s+)(\\S+)(\\s+)(\\S+)来进行替换,这五个括号里面的匹配模式就分别对应了上面的五个部分,此外需要提到一点就是()里面包裹的模式匹配到的
      字符串会被保存到分组中,一个正则表达式最多有9个组,匹配完成之后可以利用$n(n = 0….9)就可以逐个取出来使用,你可能会说了,$0到$9有10个组。对的,$0这个组默认是匹配到的整个字符串
      ,$1才是上面第一个括号里面模式对应的组,所以替换的字符串我们用的是/**\$1*/$5,就是把第一个括号里面的模式匹配到的字符串塞到/**$1*/$5里面$1的位置,
      把第五个括号里面的模式匹配到的字符串塞到/**$1*/$5里面$5的位置。然后就可以得到1后面的结果了。
    • 2:得到第一步的结果之后,我们需要向第二步结果转换,其实就是将字段名称复制了一份放到“”中,完成了变量字符串值的定义。注意后面还加了一个分号。
    • 3:得到第二步结果之后,要得到第三步骤,只需要在变量名称前面加上public static final String ,就好了
2+

喜欢该文章的用户:

  • avatar

发表评论

电子邮件地址不会被公开。

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>