Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีหาและแยกตัวเลขจาก String ใน C#

Regular Expression เป็น Pattern ที่สามารถ Match กับ Input Text ได้ .NET Framework จัดเตรียม Regular Expression Engine สำหรับ Matching แบบนี้ Pattern ประกอบด้วย Character Literals, Operators หรือ Constructs หนึ่งหรือมากกว่า

Pattern Metacharacters พื้นฐานที่ RegEx ใช้:


* = Zero or more
? = Zero or one
^ = Not (ภายใน [])
[] = Range (เช่น 0-9, a-z, A-Z)
\d = Digit (0-9)
\D = Non-digit
+ = One or more

1. ใช้ Char.IsDigit()


using System;

namespace DemoApplication {
    public class Program {
        static void Main(string[] args) {
            string str1 = "123string456";
            string str2 = string.Empty;
            int val = 0;
            
            Console.WriteLine($"String with number: {str1}");
            
            for (int i = 0; i < str1.Length; i++) {
                if (Char.IsDigit(str1[i])) {
                    str2 += str1[i];
                }
            }
            
            if (str2.Length > 0) {
                val = int.Parse(str2);
            }
            
            Console.WriteLine($"Extracted Number: {val}");
            Console.ReadLine();
        }
    }
}

Output


String with number: 123string456
Extracted Number: 123456

ในตัวอย่าง Loop ทุก Character ของ String str1 Char.IsDigit() Validate ว่า Character นั้นเป็นตัวเลขหรือไม่ และเพิ่มเข้า String ใหม่ แล้ว Parse เป็นตัวเลข

2. ใช้ Regex (แนะนำ)


using System;
using System.Text.RegularExpressions;

namespace DemoApplication {
    public class Program {
        static void Main(string[] args) {
            string str1 = "123string456";
            string str2 = string.Empty;
            int val = 0;
            
            Console.WriteLine($"String with number: {str1}");
            
            // \d+ = หนึ่งหรือหลาย Digits ติดกัน
            var matches = Regex.Matches(str1, @"\d+");
            
            foreach(var match in matches) {
                str2 += match;
            }
            
            val = int.Parse(str2);
            Console.WriteLine($"Extracted Number: {val}");
            Console.ReadLine();
        }
    }
}

Output


String with number: 123string456
Extracted Number: 123456

Regex Patterns ที่มีประโยชน์

Patternความหมายตัวอย่าง Match
\dDigit เดียว (0-9)"a1b" → "1"
\d+Digits ติดกัน 1+ ตัว"abc123def" → "123"
\d*Digits 0+ ตัว"abc" → "" (empty)
[\d\-+]+Digits, -, + (สำหรับ signed numbers)"-123.45" → "-123", "45"
\d+(\.\d+)?Integer หรือ Decimal"123", "123.45"
-?\d+(\.\d+)?Signed Integer/Decimal"-123.45", "+100"

ตัวอย่างขั้นสูง: แยกตัวเลขทุกประเภท


string input = "Price: -$1,234.56, Quantity: 10, Rate: 3.14%";
var numbers = Regex.Matches(input, @"-?\d+(?:[.,]\d+)?")
    .Cast()
    .Select(m => m.Value)
    .ToList();

// numbers: ["1,234.56", "10", "3.14"]
// ต้อง Parse เพิ่มเพื่อแปลงเป็น Numeric Types

Performance Comparison

  • Char.IsDigit + Loop: เร็วที่สุดสำหรับ String สั้น, No GC Pressure จาก Regex
  • Regex.Matches: อ่านง่าย, Flexible, เหมาะ Pattern ซับซ้อน
  • Regex.Compiled: ใช้เมื่อ Pattern ใช้ซ้ำบ่อย (Cache Compiled Regex)

// Pre-compiled Regex สำหรับ Performance
private static readonly Regex _digitRegex = new Regex(@"\d+", RegexOptions.Compiled);

public static List ExtractNumbers(string input) {
    return _digitRegex.Matches(input)
        .Cast()
        .Select(m => int.Parse(m.Value))
        .ToList();
}

การจัดการ Decimal Separator (Thai/US)


// US: 1,234.56  Thai: 1.234,56
string usNumber = "1,234.56";
string thNumber = "1.234,56";

var usFormat = new CultureInfo("en-US");
var thFormat = new CultureInfo("th-TH");

decimal usValue = decimal.Parse(usNumber, usFormat); // 1234.56
decimal thValue = decimal.Parse(thNumber, thFormat); // 1234.56