2012-04-03 135 views
-2

任何人都可以使用正則表達式模式來檢查以下內容。正則表達式

  1. xxxxxxxxxxxxxxxxxxxxxxxxxx $ S
  2. xxxxxxxxxxxxxxxxxxxxxxxxxx $ S

線,$ somewhitespacesS結束。

我想用這個作爲分隔符爲stringscanner打破長字符串(在Java)

THX

+3

是的,我們可以幫助你。你到目前爲止嘗試過什麼? [Here's](http://www.regular-expressions.info/tutorial.html)是一個很好的參考。 – Wiseguy 2012-04-03 15:10:57

+0

你使用哪種正則表達式?如果你打算在代碼中使用它,什麼語言? – Robbie 2012-04-03 15:13:28

回答

1

你可以使用這個表達式:

/\$\s+S$/ 

編輯:基於您的評論可能你需要這個:

int count = str.split("\\$\\s+S(\\n|$)").length; 

現在count將爲您提供字符串str中以\\$\\s+S結尾的格式的數量(可選地後跟換行符或文本結尾)。

+0

這隻會匹配行的末尾...不是整行,如指定的 – Robbie 2012-04-03 15:14:36

+0

希望您閱讀此行:「以$ somewhitespacesS結尾的行」 – anubhava 2012-04-03 15:15:39

+0

我做過了,它說「行」不是'$ S在行末'所以我假設他想匹配整個行。請注意,我並不打算把它變成與你的爭論,我明白OP的問題有點含糊......所以我想我們都只是盡我們所能最好的 – Robbie 2012-04-03 15:16:52

1

更新:基於來自其他答案之一的評論。看起來你正試圖計算最後有$ S的字符串中的行數。爲此,您可以使用positive lookahead這樣的:

.*(?=\$\sS) 

這裏是一個將使用這個表達式對給定subjectString,並把所有的比賽到一個數組一些Java代碼:

List<String> matchList = new ArrayList<String>(); 
Pattern regex = Pattern.compile(".*(?=\\$\\sS)"); 
Matcher regexMatcher = regex.matcher(subjectString); 
while (regexMatcher.find()) { 
    matchList.add(regexMatcher.group()); 
} 

如果再想要得到那些比賽的數量,你可以這樣做:

int count = matchList.size(); 

如果subjectString等於:

xxxxxxxxxxxxxxxxxxxxxxxxxx $ S <-- Match 
xxxxxxxxxxxxxxxxxxxxxxxxxx  <-- No Match 
xxxxxxxxxxxxxxxxxxxxxxxxxx $ S <-- Match 

// count = 2 in this case 

您可以檢出的this site一些很好的正則表達式的信息(或谷歌自己),而是幫助你理解這個特殊的正則表達式,這裏有一些評論:

"." +  // Match any single character that is not a line break character 
"*" +  // Between zero and unlimited times, as many times as possible, giving back as needed (greedy) 
"(?=" +  // Assert that the regex below can be matched, starting at this position (positive lookahead) 
    "\\$" +  // Match the character 「$」 literally 
    "\\s" +  // Match a single character that is a 「whitespace character」 (spaces, tabs, and line breaks) 
    "S" +  // Match the character 「S」 literally 
")" 
0

您可以使用像這樣:\\$\\s+S$