Java 中檢查字串不包含某些字元
假設以下字串包含特殊字元。
String str = "test*$demo";
檢查特殊字元。
Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
Matcher match = pattern.matcher(str);
boolean val = match.find();現在,如果 bool 值“val”為真,則意味著字串中包含特殊字元。
if (val == true)
System.out.println("Special characters are in the string.");示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String []args) {
String str = "test*$demo";
System.out.println("String: "+str);
Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
Matcher match = pattern.matcher(str);
boolean val = match.find();
if (val == true)
System.out.println("Special characters are in the string.");
else
System.out.println("Special characters are not in the string.");
}
}輸出
String: test*$demo Special characters are in the string.
以下是具有不同輸入的另一個示例。
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String []args) {
String str = "testdemo";
System.out.println("String: "+str);
Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
Matcher match = pattern.matcher(str);
boolean val = match.find();
if (val == true)
System.out.println("Special characters are in the string.");
else
System.out.println("Special characters are not in the string.");
}
}輸出
String: testdemo Special characters are not in the string...
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP