如何使用 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
廣告