正则表达式 Java 中的元字符


当不在括号内时,子表达式/元字符 “\b” 匹配单词边界。当在括号内时,匹配退格键 (0x08)。

范例 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "\bbecause\b";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string: ");
      String input = sc.nextLine();
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count ++;
      }
      System.out.println("Number of matches: "+count);
   }
}

输出

Enter a string:
A sentence doesn't end with because because, because is a conjunction
Number of matches: 3

范例 2

以下 Java 范例从用户读取一个字符串值并打印单词边界数。

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main( String args[] ) {
      System.out.println("Enter input string: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\b";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count ++;
      }
      System.out.println(count);
   }
}

输出

Enter input string:
Hello how are you welcome to Tutorialspoint
14

更新于: 02-02-2023

阅读 272 次

开启您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.