Home > Java > javaTutorial > Sample tutorial for learning Java regular expressions

Sample tutorial for learning Java regular expressions

WBOY
Release: 2024-01-09 21:33:57
Original
1165 people have browsed it

Sample tutorial for learning Java regular expressions

Java Regular Expression Example Tutorial

Regular Expression (Regular Expression) is a powerful tool for matching strings. It can, based on specified rules, Quickly search, match, replace, extract and other operations in given text. In Java development, regular expressions are widely used in string processing, form validation, data extraction and other fields.

This article will lead you to understand the use of regular expressions in Java through some specific code examples.

  1. Determine whether it matches

First, let’s look at a simple example to determine whether a string conforms to the rules of a regular expression. The following code demonstrates how to use regular expressions in Java for matching judgment:

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

public class RegexExample {
    public static void main(String[] args) {
        String regex = "\d+"; // 匹配数字的正则表达式
        String text = "12345";

        // 使用Pattern类和Matcher类进行匹配判断
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        if (matcher.matches()) {
            System.out.println("字符串匹配成功");
        } else {
            System.out.println("字符串匹配失败");
        }
    }
}
Copy after login

The above code first defines a regular expression that matches numbers d , and then uses the ## of the Pattern class #compileMethod is compiled into Pattern object. Next, create a Matcher object through the Pattern object, and use the matches method to determine the match. If the match is successful, print "String match successful", otherwise print "String match failed".

    Search and Extract
In addition to determining whether there is a match, regular expressions can also be used to find and extract substrings that match the rules. The following code demonstrates how to use regular expressions to find and extract URL links from text:

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

public class RegexExample {
    public static void main(String[] args) {
        String regex = "https?://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?"; // 匹配URL链接的正则表达式
        String text = "Visit my website at https://www.example.com";

        // 使用Pattern类和Matcher类进行查找和提取
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        List<String> urls = new ArrayList<>();

        while (matcher.find()) {
            String url = matcher.group();
            urls.add(url);
        }

        System.out.println("找到以下URL链接:");
        for (String url : urls) {
            System.out.println(url);
        }
    }
}
Copy after login

The above code uses a regular expression that matches URL links

https?://([\w- ] \.) [\w-] (/[\w-./?%&=]*)?, and then use the find method of the Matcher class to find and extract matches that match the regular expression substring. Each time a matching substring is found, it is added to the list and finally all found URLs are printed out.

    Replacement and splitting
In addition to searching and extracting, regular expressions can also be used to replace and split strings. The following code demonstrates how to use regular expressions to replace sensitive words in text and use regular expressions to split sentences:

import java.util.regex.Pattern;

public class RegexExample {
    public static void main(String[] args) {
        String regex = "badword1|badword2"; // 匹配敏感词的正则表达式
        String text = "This is a badword1 and badword2 example";

        // 使用正则表达式进行替换
        String replacedText = text.replaceAll(regex, "***");
        System.out.println("替换后的文本:" + replacedText);

        // 使用正则表达式进行分割
        String[] sentences = text.split("[.!?]");
        System.out.println("分割后的句子:");
        for (String sentence : sentences) {
            System.out.println(sentence.trim());
        }
    }
}
Copy after login
The above code first defines a regular expression that matches sensitive words

badword1|badword2 , and then use the replaceAll method to perform the replacement operation. Replace sensitive words in the text with *** and print the replaced text.

Next, use the

split method and the regular expression [.!?] to perform the split operation, split the text into multiple sentences based on punctuation marks, and print each sentence.

The above is an example tutorial on Java regular expressions. Through specific code examples, it introduces the basic usage of regular expressions. I hope it will help everyone understand and master the application of regular expressions in Java development. effect.

The above is the detailed content of Sample tutorial for learning Java regular expressions. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template