入力データ文字列から単語ではなく文字を削除するのに助けが必要です。以下のように、
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";
文字を一致させ、前後に文字がないことを確認する必要があります。だから一致
(?<!\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);
そして、ここに古い学校があります:
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
「義務的な」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));
このアプローチは、各単語に数字が含まれているかどうかを調べます。次に、数字以外の文字を除外し、結果から新しい文字列を作成します。それ以外の場合は、単語が必要です。