programing

문자열에서 숫자가 아닌 문자 제거

kakaobank 2023. 5. 22. 21:14
반응형

문자열에서 숫자가 아닌 문자 제거

ASP.NET C#의 문자열에서 숫자가 아닌 문자를 제거하려고 합니다.40,595 p.a.로 끝날 것입니다.40595.

감사해요.

여러 가지 방법이 있지만 이렇게 하면 됩니다(하지만 정말 큰 문자열에서 어떻게 작동하는지는 알 수 없습니다).

private static string GetNumbers(string input)
{
    return new string(input.Where(c => char.IsDigit(c)).ToArray());
}

정규 표현에 잘 어울리는 것 같아요.

var s = "40,595 p.a.";
var stripped = Regex.Replace(s, "[^0-9]", "");

"[^0-9]"로 대체할 수 있습니다.@"\D"하지만 저는 가독성이 좋습니다.[^0-9].

확장 방법이 더 나은 접근 방식이 될 것입니다.

public static string GetNumbers(this string text)
    {
        text = text ?? string.Empty;
        return new string(text.Where(p => char.IsDigit(p)).ToArray());
    }
public static string RemoveNonNumeric(string value) => Regex.Replace(value, "[^0-9]", "");

다른 옵션은...

private static string RemoveNonNumberDigitsAndCharacters(string text)
{
    var numericChars = "0123456789,.".ToCharArray();
    return new String(text.Where(c => numericChars.Any(n => n == c)).ToArray());
}

0-9만 캡처하고 나머지는 버리는 정규식을 사용합니다.정규 표현식은 처음에는 비용이 많이 들 것 같은 수술입니다.또는 다음과 같은 작업을 수행합니다.

var sb = new StringBuilder();
var goodChars = "0123456789".ToCharArray();
var input = "40,595";
foreach(var c in input)
{
  if(goodChars.IndexOf(c) >= 0)
    sb.Append(c);
}
var output = sb.ToString();

제가 생각하기에, 저는 아직 컴파일을 하지 않았습니다.

LINQ는 프레드릭이 말했듯이 옵션이기도 합니다.

C# 3.0부터는 가능한 경우 람다 식 대신 방법 그룹을 사용해야 합니다.이는 메서드 그룹을 사용하면 리디렉션이 하나 줄어들기 때문에 더 효율적이기 때문입니다.

따라서 현재 수락된 답변은 다음과 같습니다.

private static string GetNumbers(string input)
{
    return new string(input.Where(char.IsDigit).ToArray());
}
 var output = new string(input.Where(char.IsNumber).ToArray());

자, 여러분은 숫자가 무엇인지 알고 있습니다: 0123456789?문자열을 문자별로 이동합니다. 문자가 숫자인 경우 임시 문자열 끝에 고정하고, 그렇지 않은 경우 무시합니다.C# 문자열에 대해 다른 도우미 방법을 사용할 수 있지만 이 방법은 어디서나 작동하는 일반적인 방법입니다.

정규식을 사용하는 코드는 다음과 같습니다.

string str = "40,595 p.a.";

StringBuilder convert = new StringBuilder();

string pattern = @"\d+";
Regex regex = new Regex(pattern);

MatchCollection matches = regex.Matches(str);

foreach (Match match in matches)
{
convert.Append(match.Groups[0].ToString());
}

int value = Convert.ToInt32(convert.ToString()); 

허용된 답변은 훌륭하지만 NULL 값을 고려하지 않으므로 대부분의 시나리오에서 사용할 수 없습니다.

이것은 제가 대신 이러한 도우미 방법을 사용하도록 만들었습니다.첫 번째 사람은 OP에 답하고, 다른 사람들은 반대를 수행하려는 사람들에게 유용할 수 있습니다.

    /// <summary>
    /// Strips out non-numeric characters in string, returning only digits
    /// ref.: https://stackoverflow.com/questions/3977497/stripping-out-non-numeric-characters-in-string
    /// </summary>
    /// <param name="input">the input string</param>
    /// <param name="throwExceptionIfNull">if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.</param>
    /// <returns>the input string numeric part: for example, if input is "XYZ1234A5U6" it will return "123456"</returns>
    public static string GetNumbers(string input, bool throwExceptionIfNull = false)
    {
        return (input == null && !throwExceptionIfNull) 
            ? input 
            : new string(input.Where(c => char.IsDigit(c)).ToArray());
    }

    /// <summary>
    /// Strips out numeric and special characters in string, returning only letters
    /// </summary>
    /// <param name="input">the input string</param>
    /// <param name="throwExceptionIfNull">if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.</param>
    /// <returns>the letters contained within the input string: for example, if input is "XYZ1234A5U6~()" it will return "XYZAU"</returns>
    public static string GetLetters(string input, bool throwExceptionIfNull = false)
    {
        return (input == null && !throwExceptionIfNull) 
            ? input 
            : new string(input.Where(c => char.IsLetter(c)).ToArray());
    }

    /// <summary>
    /// Strips out any non-numeric/non-digit character in string, returning only letters and numbers
    /// </summary>
    /// <param name="input">the input string</param>
    /// <param name="throwExceptionIfNull">if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.</param>
    /// <returns>the letters contained within the input string: for example, if input is "XYZ1234A5U6~()" it will return "XYZ1234A5U6"</returns>
    public static string GetLettersAndNumbers(string input, bool throwExceptionIfNull = false)
    {
        return (input == null && !throwExceptionIfNull) 
            ? input 
            : new string(input.Where(c => char.IsLetterOrDigit(c)).ToArray());
    }

자세한 내용은 제 블로그의 이 게시물을 참조하십시오.

만약 당신이 VB에서 일하다가 여기에 오게 된다면, ".where"는 저에게 오류를 던졌습니다.https://forums.asp.net/t/1067058.aspx?Trimming+a+string+to+remove+special+non+numeric+characters 에서 확인할 수 있습니다.

Function ParseDigits(ByVal inputString as String) As String
  Dim numberString As String = ""
  If inputString = Nothing Then Return numberString

  For Each c As Char In inputString.ToCharArray()
    If c.IsDigit Then
      numberString &= c
    End If
  Next c

  Return numberString
End Function

숫자가 아닌 모든 문자를 제거합니다.

Public Function OnlyNumeric(strIn As String) As String
      Try
            Return Regex.Replace(strIn, "[^0-9]", "")
      Catch
            Return String.Empty
      End Try
End Function

언급URL : https://stackoverflow.com/questions/3977497/stripping-out-non-numeric-characters-in-string

반응형