นิพจน์ทั่วไปเป็นรูปแบบที่สามารถจับคู่กับข้อความที่ป้อนได้ เฟรมเวิร์ก .Net จัดเตรียมเอ็นจินนิพจน์ทั่วไปที่อนุญาตการจับคู่ดังกล่าว รูปแบบประกอบด้วยตัวอักษร ตัวดำเนินการ หรือโครงสร้างตั้งแต่หนึ่งตัวขึ้นไป
ต่อไปนี้คืออักขระเมตารูปแบบพื้นฐานที่ใช้โดย RegEx -
* = zero or more ? = zero or one ^ = not [] = range
สัญลักษณ์ ^ ใช้เพื่อระบุว่าไม่ใช่เงื่อนไข
วงเล็บ [] หากเราต้องการให้ค่าช่วงเช่น 0 - 9 หรือ a-z หรือ A-Z
การใช้ 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();
}
}
} ผลลัพธ์
String with number: 123string456 Extracted Number: 123456
ในตัวอย่างข้างต้น เราจะวนลูปอักขระทั้งหมดของสตริง str1 TheChar.IsDigit() จะตรวจสอบว่าอักขระนั้น ๆ เป็นตัวเลขหรือไม่ และเพิ่มเข้าไปในสตริงใหม่ซึ่งจะแยกวิเคราะห์เป็นตัวเลขในภายหลัง
การใช้ 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}");
var matches = Regex.Matches(str1, @"\d+");
foreach(var match in matches){
str2 += match;
}
val = int.Parse(str2);
Console.WriteLine($"Extracted Number: {val}");
Console.ReadLine();
}
}
} ผลลัพธ์
String with number: 123string456 Extracted Number: 123456
ในตัวอย่างข้างต้น เราใช้นิพจน์ทั่วไป (\d+) เพื่อแยกเฉพาะตัวเลขจากสตริง str1