Show toolbar

2012年12月3日 星期一

C# WPF RegEx Check Number

標題:使用RegEx進行數字比對
C# (MainWindow.xaml.cs):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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):
1
2
3
4
5
6
7
8
9
<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判斷字串是否為數字之基礎範例。