是否存在空格的正则表达式

时间:2013-07-13 14:20:31

标签: java regex

我试图使一个字符串声明的正则表达式,其中整个代码文件空间可以在声明之前的某个地方出现,并且在某些地方声明从行的左边开始,没有任何空格......我怎么能处理那个空间?

就像..

  1. < --- spaces -------> String sVariable; //声明前的空格//
  2. String sVariable; //声明之前不存在的空格//
  3. 我试过像 -  strLine.toUpperCase()。匹配(“。 STRING \ s。”)---但它指向第一个声明。如何声明正则表达式,使其指向两者..

3 个答案:

答案 0 :(得分:0)

您可以尝试使用 1

strLine.matches("(?i)\\s*STRING")

通常,X*表示X 0次或更多次(?i)是忽略大小写的标志。

虽然您可能还想考虑

strLine.trim().equalsIgnoreCase("STRING")

1 请注意,如果您要反复使用特定的正则表达式,则应通过Pattern.compile()预编译并使用Matcher

答案 1 :(得分:0)

您需要这样的内容来考虑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的那个。

答案 2 :(得分:0)

就这样使用String.matches()

if (strLine.matches("\\s*String\\s.*"))

matches()的正则表达式必须与整个字符串匹配,这就是为什么最后有.*的原因。

此正则表达式还允许在“String”

之后使用非空格字符,例如制表符