2012-11-19 23 views
0

我有很多的空间分隔字符串交易的操作,我正在寻找字符串是一个正则表达式,如果前第一空间前两个字符串以大写字母和意志开始匹配的功能,这将触发通如果不是,则返回false。正则表达式

例子:

"AL_RIT_121 PA_YT_32 rit cell 22 pulse" 

将返回true,因为前两个子AL_RIT_121PA_YT_32开始用大写字母AP分别

"AL_RIT_252 pa_YT_21 mal cell reg 32 1 ri" 

也将返回false p是小写。

+0

那你试试? –

+0

你的问题不会使你感兴趣。你在“AL_RIT_121”和“PA_YT_32”之间的第一个空格 –

回答

3

只需string.matches("[A-Z]\\w+ [A-Z].*")

+0

感谢它的模式,它满足我的标准:) – Avishek

5
Pattern.compile("^\\p{Lu}\\S*\\s+\\p{Lu}") 

将与.find()方法一起使用。没有理由对一个前缀测试使用matches,但如果你有一个外部的约束,只是做

Pattern.compile("^\\p{Lu}\\S*\\s+\\p{Lu}.*", Pattern.DOTALL) 

要打破下来:

  1. ^字符串的开头匹配,
  2. \\p{Lu}匹配任何大写字母,
  3. \\S*匹配零个或多个非空格字符,包括_
  4. \\s+匹配一个或多个空格字符,并且
  5. 第二\\p{Lu}大写字母开始的第二个字相匹配。

在第二个变体中,.*Pattern.DOTALL结合匹配其余的输入。

+0

你并不需要在方括号中放入'\ p {Lu}';像'\ s'和'\ S',它可以独立使用。它是'DOTALL',而不是'DOT_ALL'。我几乎总是不得不用Python和Java来查看它们,但是它们都是拼写而不用下划线。 –

+0

@AlanMoore,我整合了你的更正。谢谢。 –

+0

非常感谢大家,提供的正则表达式对我来说非常合适:) – Avishek

1

您可以使用特定的正则表达式,如果这两个例子说明你的输入格式:

^(?:[A-Z]+_[A-Z]+_\d+\s*)+ 

这意味着:

^   - Match the beginning of the string 
(?:   - Start a non-capturing group (used to repeat the following) 
    [A-Z]+ - Match one or more uppercase characters 
    _  - Match an underscore 
    [A-Z]+ - Match one or more uppercase characters 
    _  - Match an underscore 
    \d+  - Match one or more decimals (0-9) 
    \s*  - Match zero or more space characters 
)+   - Repeat the above group one or more times 

你可以使用它在Java中这样:

Pattern pattern = Pattern.compile("^(?:[A-Z]+_[A-Z]+_\\d+\\s*)+"); 
Matcher matcher = p.matcher(inputString); 
if(matcher.matches()) { 
    System.out.println("Match found."); 
} 
1

检查了这一点:

public static void main(String[] args) 
{ 
    String text = "AL_RIT_121 pA_YT_32 rit cell 22 pulse"; 

    boolean areFirstTwoWordsCapitalized = areFirstTwoWordsCapitalized(text); 

    System.out.println("areFirstTwoWordsCapitalized = <" + areFirstTwoWordsCapitalized + ">"); 

} 

private static boolean areFirstTwoWordsCapitalized(String text) 
{ 
    boolean rslt = false; 

    String[] words = text.split("\\s"); 

    int wordIndx = 0; 

    boolean frstWordCap = false; 
    boolean scndWordCap = false; 

    for(String word : words) 
    { 
     wordIndx++; 

     //System.out.println("word = <" + word + ">"); 

     Pattern ptrn = Pattern.compile("^[A-Z].+"); 

     Matcher mtchr = ptrn.matcher(word); 

     while(mtchr.find()) 
     { 
      String match = mtchr.group(); 

      //System.out.println("\tMatch = <" + match + ">"); 

      if(wordIndx == 1) 
      { 
       frstWordCap = true; 
      } 
      else if(wordIndx == 2) 
      { 
       scndWordCap = true; 
      } 
     } 
    } 

    rslt = frstWordCap && scndWordCap; 

    return rslt; 
} 
1

试试这个:

public class RegularExp 
{ 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     String regex = "[A-Z][^\\s.]*\\s[A-Z].*"; 
     String str = "APzsnnm lmn Dlld"; 
     System.out.println(str.matches(regex)); 

    } 

}