2011-11-29 91 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