Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern to extract version number from string

Tags:

c#

regex

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

like image 459
Zain Ali Avatar asked Jan 21 '12 18:01

Zain Ali


People also ask

How do you get a number from a string in RegEx?

Python Regex – Get List of all Numbers from String. To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string.

How do I find a specific pattern in RegEx?

RegEx uses metacharacters in conjunction with a search engine to retrieve specific patterns. Metacharacters are the building blocks of regular expressions. For example, “\d” in a regular expression is a metacharacter that represents a digit character.

How do you check if a number is regular expression?

Validating Numeric Ranges. If you're using the regular expression to validate input, you'll probably want to check that the entire input consists of a valid number. To do this, replace the word boundaries with anchors to match the start and end of the string: ^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$.


4 Answers

\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.

like image 150
Olivier Jacot-Descombes Avatar answered Nov 07 '22 11:11

Olivier Jacot-Descombes


Try:

Regex pattern = new Regex("\d+(\.\d+)+");
Match m = pattern.Match(a);
string version = m.Value;
like image 37
Mithrandir Avatar answered Nov 07 '22 13:11

Mithrandir


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.

like image 34
Sufian Latif Avatar answered Nov 07 '22 13:11

Sufian Latif


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

\d+(\.\d+)+
like image 3
Douglas Avatar answered Nov 07 '22 12:11

Douglas