0

我需要帮助从传入的数据字符串中删除字母而不是单词。像下面这样,

String A = "1 2 3A 4 5C 6 ABCD EFGH 7 8D 9";

String A = "1 2 3 4 5 6 ABCD EFGH 7 8 9";
4

3 回答 3

4

您需要匹配一个字母并确保前后没有字母。所以匹配

(?<!\p{L})\p{L}(?!\p{L})

并替换为空字符串。

在 C# 中:

string s = "1 2 3A 4 5C 6 ABCD EFGH 7 8D 9";
string result = Regex.Replace(s, @"(?<!\p{L}) # Negative lookbehind assertion to ensure not a letter before
                                   \p{L}      # Unicode property, matches a letter in any language
                                   (?!\p{L})  # Negative lookahead assertion to ensure not a letter following
                                  ", String.Empty, RegexOptions.IgnorePatternWhitespace);
于 2012-11-19T14:18:27.780 回答
0

“强制性” Linq 方法:

string[] words = A.Split();
string result = string.Join(" ", 
        words.Select(w => w.Any(c => Char.IsDigit(c)) ? 
        new string(w.Where(c => Char.IsDigit(c)).ToArray()) : w));

这种方法查看每个单词是否包含一个数字。然后它过滤掉非数字字符并从结果中创建一个新字符串。否则它只需要这个词。

于 2012-11-19T14:26:54.977 回答
0

老派来了:

Dim A As String = "1 2 3A 4 5C 6 ABCD EFGH 7 8D 9"
Dim B As String = "1 2 3 4 5 6 ABCD EFGH 7 8 9"
Dim sb As New StringBuilder
Dim letterCount As Integer = 0
For i = 0 To A.Length - 1
  Dim ch As Char = CStr(A(i)).ToLower
  If ch >= "a" And ch <= "z" Then
    letterCount += 1
  Else
    If letterCount > 1 Then sb.Append(A.Substring(i - letterCount, letterCount))
    letterCount = 0
    sb.Append(A(i))
  End If
Next
Debug.WriteLine(B = sb.ToString) 'prints True
于 2012-11-19T14:50:46.247 回答