zoukankan      html  css  js  c++  java
  • Java

    验证

    简单验证

    String regex = "\d{4}-\d{2}-\d{2}";
    String input = "2016-01-01";
    assertTrue(input.matches(regex));
    assertTrue(Pattern.matches(regex, input));

    提取

    String regex = "\d{4}-\d{2}-\d{2}";
    String input = "2016-01-01, 2016-02-02. [2016-03-03]";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }

    替换

    简单替换

    String regex = "(\d{4})-(\d{2})-(\d{2})";
    String replacement = "$2/$3/$1";
    String input = "2016-01-15, 2016-02-15.";
    String actual = input.replaceAll(regex, replacement);
    String expected = "01/15/2016, 02/15/2016.";
    assertEquals(expected, actual);

    使用 Pattern 对象,方便反复使用

    String regex = "(\d{4})-(\d{2})-(\d{2})";
    String replacement = "$2/$3/$1";
    String input = "2016-01-15, 2016-02-15.";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    String actual = matcher.replaceAll(replacement);
    String expected = "01/15/2016, 02/15/2016.";
    assertEquals(expected, actual);

    切分

    简单切分

    String regex = "\s+";
    String input = "a  b	c";
    String[] actuals = input.split(regex);
    String[] expecteds = new String[] {"a", "b", "c"};
    assertArrayEquals(expecteds, actuals);

    使用 Pattern 对象,方便反复使用

    String regex = "\s+";
    String input = "a  b	c";
    Pattern pattern = Pattern.compile(regex);
    String[] actuals = pattern.split(input);
    String[] expecteds = new String[] {"a", "b", "c"};
    assertArrayEquals(expecteds, actuals);
  • 相关阅读:
    RabbitMQ知识点整理2-相关概念介绍
    RabbitMQ知识点整理1-生产和消费消息
    Java自学-图形界面 Swing中的线程
    Java自学-图形界面 日期控件
    Java自学-图形界面 表格
    Java自学-图形界面 工具栏
    WebStorm 2020.2.3 破解(Mac,windows,Linux)
    消息队列的使用场景
    有关建立虚拟环境的总结
    性能测试-Locust分布式执行
  • 原文地址:https://www.cnblogs.com/huey/p/5531065.html
Copyright © 2011-2022 走看看