首页 > 编程语言 > 详细

java regular expression

时间:2020-07-20 17:26:58      阅读:72      评论:0      收藏:0      [点我收藏+]

Attention

技术分享图片

Example

matches() 尝试匹配整个字符串 ?

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        Pattern pattern1 = Pattern.compile("\\w+"); // \w : 字母、数字、下划线
        Matcher matcher = pattern1.matcher("my_cat_is_sitting_on_the_mat");
        System.out.println(matcher.matches()); // true
    }
}

find() 查找是否有子串匹配 , find()方法可以多次使用

public static void main(String[] args) {
        Pattern pattern1 = Pattern.compile("cat");
        Matcher matcher = pattern1.matcher("my_cat_is_sitting_on_the_mat");
        System.out.println(matcher.matches()); // false

        System.out.println(matcher.find()); // true
    }

find() group()
技术分享图片


技术分享图片


技术分享图片

replaceAll() && replaceFirst()

 @Test
    public void test2(){
        Pattern pattern = Pattern.compile("[0-9]");
        Matcher matcher = pattern.matcher("I have 3000 dollars.");
        
        String string = matcher.replaceAll("*");
        System.out.println(string); // I have **** dollars.
    }

@Test
    public void test2(){
        Pattern pattern = Pattern.compile("[0-9]");
        Matcher matcher = pattern.matcher("I have 3000 dollars.");

        String string1 = matcher.replaceFirst("*");
//        String string = matcher.replaceAll("*");
        System.out.println(string1); // I have *000 dollars.

split


@Test
    public void testSplit(){
        String str = "1,2,3,4,5";
        String[] split = str.split(",");
        System.out.println(Arrays.toString(split));  // [1, 2, 3, 4, 5]
    }

    @Test
    public void testSplit2(){
        String str = "1ada4dfs6fdfs78sdesf";
        String[] split = str.split("[a-z]+"); // here don‘t use *, or you‘ll have : [1, , 4, , 6, , 7, 8]
        System.out.println(Arrays.toString(split)); // [1, 4, 6, 78]
    }

java regular expression

原文:https://www.cnblogs.com/nedrain/p/13345673.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!