Java如何在正则表达式中使用逻辑OR运算符?

您可以使用|运算符(逻辑或)来匹配|运算符左侧或右侧的字符或表达式。例如,(t|T)将匹配t或匹配T输入字符串。

package org.nhooo.example.regex;

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

public class LogicalOrRegexDemo {
    public static void main(String[] args) {
        // 定义将搜索字符“ t”或“ T”的正则表达式
        String regex = "(t|T)";

        // 编译模式并获得匹配对象。
        Pattern pattern = Pattern.compile(regex);
        String input = "The quick brown fox jumps over the lazy dog";
        Matcher matcher = pattern.matcher(input);

        // 查找每个匹配并打印
        while (matcher.find()) {
            System.out.format("Text \"%s\" found at %d to %d.%n",
                matcher.group(), matcher.start(), matcher.end());
        }
    }
}

该程序将显示以下结果:

Text "T" found at 0 to 1.
Text "t" found at 31 to 32.