如何在Java字符串中搜索模式?
Java提供了 java.util.regex包,用于与正则表达式进行模式匹配。然后,您可以使用此软件包的类和方法在Java字符串中搜索模式。
示例
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { public static void main( String args[] ) { String line = "This order was placed for QT3000! OK?"; String pattern = "(.*)(\\d+)(.*)"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(0)); System.out.println("Found value: " + m.group(1)); System.out.println("Found value: " + m.group(2)); }else{ System.out.println("NO MATCH"); } } }
输出结果
Found value: This order was placed for QT3000! OK? Found value: This order was placed for QT300 Found value: 0