2011-11-29 106 views
5

如何識別包含可能包含數字的正則表達式的單詞。 所以我想捕捉「string1」,「12inches」,「log4net」。但不是12/11/2011或18? 不幸\b[\p{L}\d\p{M}]+\b也抓數字。包含數字的單詞

回答

2

此:

Regex regexObj = new Regex(@"\b(?=\S*[a-z])\w+\b", RegexOptions.IgnoreCase); 
    Match matchResults = regexObj.Match(subjectString); 
    while (matchResults.Success) { 
     // matched text: matchResults.Value 
     // match start: matchResults.Index 
     // match length: matchResults.Length 
     matchResults = matchResults.NextMatch(); 
    } 

來考慮。

" 
\b   # Assert position at a word boundary 
(?=   # Assert that the regex below can be matched, starting at this position (positive lookahead) 
    \S   # Match a single character that is a 「non-whitespace character」 
     *   # Between zero and unlimited times, as many times as possible, giving back as needed (greedy) 
    [a-z]  # Match a single character in the range between 「a」 and 「z」 
) 
\w   # Match a single character that is a 「word character」 (letters, digits, etc.) 
    +   # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
\b   # Assert position at a word boundary 
" 
+0

謝謝。其實我有一個更強硬的問題:我需要用空格或連字符來識別短語,並且有這個:(?<= \ b([\ p {L} \ p {M}] + | \ s)\ b)[\小號\ p {PD} \ S] +(?= \ b [\ p {L} \ p {M}] + \ b)中。左括號和右括號意味着一些詞(可以有變音)。現在我看到你也插入了一些前向參考。 – Nickolodeon

+0

@Nickolodeon我認爲你應該編輯你的問題,因爲我的答案答案。請張貼一些適當的輸入/輸出樣本,以便我們提供幫助。 – FailedDev

+0

好吧,對不起,我想簡化這個問題,所以我只想問一部分問題。我需要1)Robocop - 3 => Robocop3。 2)Hello 2 => Hello2 3)Hello world => Helloworld。如果沒有相鄰的數字或日期,那就是刪除空格或連字符。 – Nickolodeon

0

你想匹配一個單詞,其中包含字母和數字嗎?這應該工作:\b(\w+\d+|\d+\w+)[\w\d]+\b

相關問題