简体   繁体   English

正则表达式匹配确切的版本短语

[英]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我正在尝试获取非预览版的最新版本(版本号后没有文本),所以结果应该是: v1.0.3

I used this grep: grep -m1 "[v\d+\.\d+.\d+$]"我使用了这个 grep: grep -m1 "[v\d+\.\d+.\d+$]"

but it still outputs: v1.0.3-preview2但它仍然输出: v1.0.3-preview2

what I could be missing here?我在这里可能会错过什么?

To return first match for pattern v<num>.<num>.<num> , use:要返回模式v<num>.<num>.<num>的第一个匹配项,请使用:

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 grep | sort -V | head as: grep | sort -V | head为:

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 v : 匹配v
  • [0-9]+ : Match 1+ digits [0-9]+ : 匹配 1+ 个数字
  • (\.[0-9]+){2} : Match a dot followed by 1+ dots. (\.[0-9]+){2} :匹配一个点,后跟 1+ 个点。 Repeat this group 2 times重复这组 2 次
  • $ : End $ : 结束

To match the digits with grep, you can use要将数字与 grep 匹配,您可以使用

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您可以尝试遵循awk代码。

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. 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.请记住, $在 shell 脚本中的双引号字符串中具有特殊含义,需要进行转义。

The boundary characters need to be outside of any group ( [] ).边界字符需要任何组( [] )之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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