TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Guest User
Tech Writer
48
11.8k
Help with regular expression for negative real numbers.
Aug 14 2019 10:02 AM
I would like to make a regular expression that limits the textboxes I have to negative real numbers. Unfortunately, the best I have been able to do is to limit the text box to numbers only. I have tried several "working" examples from around the web, but none of them worked for me. Here is my code based on my book and how I would think I should build the regular expression.
using
System.Text.RegularExpressions;
using
System.Windows;
using
System.Windows.Input;
namespace
WPF_Test_Unit
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public
partial
class
MainWindow : Window
{
public
MainWindow()
{
InitializeComponent();
this
.SizeToContent = SizeToContent.WidthAndHeight;
}
private
void
CheckForNumber(
object
sender, TextCompositionEventArgs e)
{
Regex regex =
new
Regex(@
"\-?\d+\.?\d+"
);
e.Handled = !regex.IsMatch(e.Text);
}
}
}
My idea is that I would need 0 or 1 negative sign "-", then one or more digits, an optional decimal "." and then one or more digits trailing the decimal point.
Below is the XAML that uses the function.
<
TextBox
Grid.Row
=
"3"
Grid.Column
=
"1"
VerticalAlignment
=
"Center"
PreviewTextInput
=
"CheckForNumber"
HorizontalAlignment
=
"Center"
FontSize
=
"20"
Width
=
"170"
Height
=
"40"
/>
I have tried many combinations of regular expressions, but the only results I can get with preventing characters in the textbox a numbers-only situation. Trying to remove (or allow) other characters seems not to work.
Reply
Answers (
4
)
I’m getting errors
Drop down command to tool bar