Ask Your Question
1

How do I use C# Regex to ensure that a string has one dot followed by numbers?

asked 2021-08-21 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-06-27 10:00:00 +0000

bukephalos gravatar image

You can use the following C# regex pattern to ensure that a string has one dot followed by numbers:

^[0-9]+(\.[0-9]+)?$

Explanation:

  • ^ : Start of the string
  • [0-9]+ : Match one or more digits
  • (\.[0-9]+)? : Match a dot followed by one or more digits, optionally (the ? makes the group optional)
  • $ : End of the string

Example usage:

string input = "3.1415";
bool match = Regex.IsMatch(input, "^[0-9]+(\\.[0-9]+)?$"); // true

input = "42";
match = Regex.IsMatch(input, "^[0-9]+(\\.[0-9]+)?$"); // false

input = "3.14.15";
match = Regex.IsMatch(input, "^[0-9]+(\\.[0-9]+)?$"); // false
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-21 11:00:00 +0000

Seen: 19 times

Last updated: Jun 27 '22