Java regex 程式,用於按每個空格和標點符號分割字串。
正則表示式 "[!._,'@?//s]" 匹配所有標點符號和空格。
示例
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main( String args[] ) {
String input = "This is!a.sample"text,with punctuation!marks";
Pattern p = Pattern.compile("[!._,'@?//s]");
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
}輸出
Number of matches: 8
String 類中的split()方法接受一個表示正則表示式的值,並將當前字串分割為由標記(單詞)組成的陣列,將兩次匹配之間出現的字串視為一個標記。
例如,如果你將單個空格“ ”作為分隔符傳遞給此方法並嘗試分割一個字串。此方法將兩個空格之間的單詞視為一個標記,並返回當前字串中單詞(空格之間)的陣列。
因此,若要按每個空格和標點符號分割字串,請對其呼叫 split() 方法,並傳遞上述指定正則表示式作為引數。
示例
import java.util.Scanner;
import java.util.StringTokenizer;
public class RegExample {
public static void main( String args[] ) {
String regex = "[!._,'@? ]";
System.out.println("Enter a string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
StringTokenizer str = new StringTokenizer(input,regex);
while(str.hasMoreTokens()) {
System.out.println(str.nextToken());
}
}
}輸出
Enter a string: This is!a.sample text,with punctuation!marks@and_spaces This is a sample text with punctuation marks and spaces
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP