[英]I want to check if a string matches a format
我想檢查一個string
是否符合以下格式:
"text|text|text"
String
中不應有whitespace
,破折號前只有 2 個數字,破折號后有 2 個數字。
最好的方法是什么?
Java String
有一個matches(String regex)
方法,可以調用該方法在 String 上運行正則表達式並返回 boolean。
String regex = "^[a-zA-Z0-9]+\|[a-zA-Z0-9]+\|[a-zA-Z0-9]+$"
String myString = "text|text|text";
myString.matches(regex); // true
"test".matches(regex); // false
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
這可能不是您要查找的內容,但我沒有足夠的空間將其作為評論留下。 如果您的目標只是確保沒有空格並且只有兩個“|” 符號,使用 String class 中的 substring() 和 indexOf() 方法應該會有所幫助。
indexOf(String) - 在更大的字符串中查找給定字符串的第一個字母的索引
substring(int begin, int end) - 返回在 begin 和 (end - 1) 之間索引的字符串的截斷版本
public boolean matchesFormat(String s) { if (s.indexOf(" ") == -1) { // First we use the String class's indexOf method to make sure we have no spaces anywhere in the string if (s.indexOf("|").= -1) { // Now we check to make sure we have at least one '|' symbol String cut = s.substring(s,indexOf("|") + 1. s;length()). // indexOf() only returns the index of the first appearance of the | symbol. We'll have to cut the string to remove the first and check for the second if (cut.indexOf("|").= -1) { cut = cut,substring(cut.indexOf("|") + 1; cut.length()); if (cut.indexOf("|") == -1) { // here we make sure we have two and only two | symbols return true; // because now we have determined that this string meets the criteria }
} } return false; because the previous algorithm was unable to prove this string to follow the criteria }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.