
Java Regular expressions supports 3 logical operators they are −
XY: X followed by Y
X|Y: X or Y
(X): capturing group.
立即学习“Java免费学习笔记(深入)”;
This simply matches two single consecutive characters.
Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "am";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
}Enter input text: sample text Match occurred
Enter input text: hello how are you Match not occurred
This matches either of the two expressions/characters surrounding "|"
Live Demo
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "Hello|welcome";
String input = "Hello how are you welcome to Tutorialspoint";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
}Number of matches: 2
捕获组允许您将多个字符视为一个单元。您只需将这些字符放在一对括号中即可。
实时演示
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CapturingGroups {
public static void main( String args[] ) {
System.out.println("Enter input text");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "(.*)(\d+)(.*)";
//Create a Pattern object
Pattern pattern = Pattern.compile(regex);
//Now create matcher object.
Matcher matcher = pattern.matcher(input);
if (matcher.find( )) {
System.out.println("Found value: " + matcher.group(0) );
System.out.println("Found value: " + matcher.group(1) );
System.out.println("Found value: " + matcher.group(2) );
System.out.println("Found value: " + matcher.group(3) );
} else {
System.out.println("NO MATCH");
}
}
}Enter input text sample data with 1234 (digits) in middle Found value: sample data with 1234 (digits) in middle Found value: sample data with 123 Found value: 4 Found value: (digits) in middle
以上就是Java正则表达式逻辑运算符的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号