[英]Regular Expression for spaces present or not
我試圖對字符串聲明進行正則表達式,其中整個代碼文件空間可以在聲明之前的某個位置出現,並且在某些地方聲明從行的左側開始,沒有任何空格...我該如何處理這些空格?
就像..
我已經嘗試過-strLine.toUpperCase()。matches(“。 STRING \\ s。 ”)---但它指向第一個聲明。 如何聲明正則表達式,使其既指向又指向..
您可以嘗試使用1
strLine.matches("(?i)\\s*STRING")
通常, X*
表示X
0或更多次 。 (?i)
是忽略大小寫的標志。
雖然您可能還想考慮
strLine.trim().equalsIgnoreCase("STRING")
1請注意,如果要重復使用特定的正則表達式,則應通過Pattern.compile()
對其進行預編譯並使用Matcher
。
您需要類似以下內容來說明String
之前的空格和緊隨其后的空格: \\\\s*String\\\\s+(\\\\w+)
(它還將捕獲變量名稱。
測試程序:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
static final Pattern stringDeclaration = Pattern.compile( "\\s*String\\s+(\\w+)" );
static void match( String s )
{
Matcher m = stringDeclaration.matcher( s );
if( m.find() )
System.out.println( "Found variable: " + m.group(1) );
else
System.out.println( "No match for " + s );
}
public static void main(String[] args) {
match( " String s1;" );
match( "String s2;" );
match( " String s3;" );
match( " String s4 ;" );
match( " String s5; " );
}
}
還有一些在線正則表達式測試器。 我喜歡http://www.regexplanet.com/advanced/java/index.html上的那個。
像這樣使用String.matches()
:
if (strLine.matches("\\s*String\\s.*"))
matchs matches()
的正則表達式必須與整個字符串匹配,因此這就是為什么末尾帶有.*
的原因。
此正則表達式還允許在“字符串”之后添加非空格字符,例如制表符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.