我需要帮助删除字母而不是输入数据字符串中的字。如下所示,
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";
答案 0 :(得分: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);
答案 1 :(得分: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));
此方法查看每个单词是否包含数字。然后它过滤掉非数字字符并从结果中创建一个新字符串。否则它就是这个词。
答案 2 :(得分: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