简体   繁体   中英

Regex needed for optional last digit

I am trying to figure out a regex for a version parser. I need to parse a version containing a major.minor.patch.build version string with 3 to 4 digits with the last (4th) digit optional.

For example the version could be: 1.2.3.4 or 1.2.3

I have my regex as the following, but it fails for 1.2.3 version string:

regex = "(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)?"

Also, do I need the double back slashes ?

The following should do what you want:

(\d+)\.(\d+)\.(\d+)(\.(\d+))?

\\d matches any single number <=> [0-9]

\\. to match the . character (a single . in a regex matches any single character)

You can prepend '^' and append '$' to the regex to ensure there's no garbage before or after your version.

In your regex you have to make the last part \\.(\\d+) including the dot optional or else it would match 1.2.3.4 but also 1.2.3.

Try it like this with an optional last group where the dot and the digits are optional:

^\\d+\\.\\d+\\.\\d+(?:\\.\\d+)?$

Or with capturing groups and the last is a non capturing group with a dot and a capturing group for the last digits:

^(\\d+)\\.(\\d+)\\.(\\d+)(?:\\.(\\d+))?$

Instead of using anchors ^ and $ you could use a word boundary \\b

There is no programming language specified concerning the double back slashes but what might help is when you open the regex101 demo link , there is a link under tools -> code generator where you can select a programming language. Perhaps that could be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM