C# (MainWindow.xaml.cs):
using System; using System.Windows; using System.Text.RegularExpressions; //RegEx namespace WPFRegEx { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public void CheckRegEx(string text) { Regex regex = new Regex("^[0-9]+$"); //建立RegEx規則 Match result = regex.Match(text); //字串比對 if (result.Success) { System.Windows.MessageBox.Show("True"); } else { System.Windows.MessageBox.Show("False"); } } private void btn_Click(object sender, RoutedEventArgs e) { CheckRegEx(tbx.Text); } } }WPF (MainWindow.xaml.cs):
<Window x:Class="WPFRegEx.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <TextBox Height="30" Margin="20,20,20,0" Name="tbx" VerticalAlignment="Top" /> <Button Content="Button" Height="30" Margin="20,70,20,0" Name="btn" VerticalAlignment="Top" Click="btn_Click" /> </Grid> </Window>
範例結果:
說明:
在C# WPF使用RegEx判斷字串是否為數字之基礎範例。
沒有留言:
張貼留言