简体   繁体   中英

Regex to match exact version phrase

I have versions like:

v1.0.3-preview2
v1.0.3-sometext
v1.0.3
v1.0.2
v1.0.1

I am trying to get the latest version that is not preview (doesn't have text after version number), so result should be: v1.0.3

I used this grep: grep -m1 "[v\d+\.\d+.\d+$]"

but it still outputs: v1.0.3-preview2

what I could be missing here?

To return first match for pattern v<num>.<num>.<num> , use:

grep -m1 -E '^v[0-9]+(\.[0-9]+){2}$' file

v1.0.3

If you input file is unsorted then use grep | sort -V | head grep | sort -V | head grep | sort -V | head as:

grep -E '^v[0-9]+(\.[0-9]+){2}$' f | sort -rV | head -1

When you use ^ or $ inside [...] they are treated a literal character not the anchors.

RegEx Details:

  • ^ : Start
  • v : Match v
  • [0-9]+ : Match 1+ digits
  • (\.[0-9]+){2} : Match a dot followed by 1+ dots. Repeat this group 2 times
  • $ : End

To match the digits with grep, you can use

grep -m1 "v[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+$" file

Note that you don't need the [ and ] in your pattern, and to escape the dot to match it literally.

With awk you could try following awk code.

awk 'match($0,/^v[0-9]+(\.[0-9]+){2}$/){print;exit}' Input_file

Explanation of awk code: Simple explanation of awk program would be, using match function of awk to match regex to match version, once match is found print the matched value and exit from program.

Regular expressions match substrings, not whole strings. You need to explicitly match the start ( ^ ) and end ( $ ) of the pattern.

Keep in mind that $ has special meaning in double quoted strings in shell scripts and needs to be escaped.

The boundary characters need to be outside of any group ( [] ).

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