18

I want to extract version number from string.

a string =  "Tale: The  Secrets 1.6"

b string=" The 34. Mask 1.6.98";

So for a version number is 1.6 and for b is 1.6.98

2
  • 2
    This all sort of depends on your defenition of version number right? 1.6 isn't a standard version number in c#, it'd be like 1.6.0.0. What other kinds of version numbers do you plan to encounter? Does a single digit count as a version number? Will your strings have digits other than version numbers that you need to account for? How about using a regular expression to extract any number followed by a period: (([0-9]+)\.?)+ and pass it to the Version class which can take a string in the constructor? Commented Jan 21, 2012 at 18:49
  • See stackoverflow.com/a/67308239/670028 Commented Apr 28, 2021 at 21:39

4 Answers 4

43
\d+(\.\d+)+

\d+         : one or more digits
\.           : one point
(\.\d+)+ : one or more occurences of point-digits

Will find

2.5
3.4.567
3.4.567.001

But will not find

12
3.
.23

If you want to exclude decimal numbers like 2.5 and expect a version number to have at least 3 parts, you can use a quantifier like this

\d+(\.\d+){2,}

After the comma, you can specify a maximum number of ocurrences.

Sign up to request clarification or add additional context in comments.

Comments

10

Try:

Regex pattern = new Regex("\d+(\.\d+)+");
Match m = pattern.Match(a);
string version = m.Value;

1 Comment

That regex would also match dot-terminated numbers, such as 34..
7

You can write

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

This should match the format. The $ is for matching at the end, can be dropped if not needed.

1 Comment

If the version number parts are separated with _, \. should be replaced with _: [0-9]+(_[0-9]+)+$ (referring to this duplicate).
3

By version number, do you mean any sequence of digits interspersed with dots?

\d+(\.\d+)+

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.