您好,欢迎访问一九零五行业门户网

Java正则表达式逻辑运算符

java regular expressions supports 3 logical operators they are −
xy: x followed by y
x|y: x or y
(x): capturing group.
xy: x followed by ythis simply matches two single consecutive characters.
example 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"); } }}
output 1的中文翻译为:输出 1enter input text:sample textmatch occurred
output 2enter input text:hello how are youmatch not occurred
x|ythis matches either of the two expressions/characters surrounding "|"
example 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
(x): 捕获组捕获组允许您将多个字符视为一个单元。您只需将这些字符放在一对括号中即可。
示例 实时演示
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 textsample data with 1234 (digits) in middlefound value: sample data with 1234 (digits) in middlefound value: sample data with 123found value: 4found value: (digits) in middle
以上就是java正则表达式逻辑运算符的详细内容。
其它类似信息

推荐信息