简体   繁体   English

正则表达式匹配特定模式

[英]regex match specific pattern

I have 我有

[root@centos64 ~]# cat /tmp/out
[
  "i-b7a82af5",
  "i-9d78f4df",
  "i-92ea58d0",
  "i-fa4acab8"
]

I would like to pipe though sed or grep to match the format "x-xxxxxxxx" ie a mix of az 0-9 always in 1-[8 chars length], and omit everything else 我想通过sed或grep传递管道以匹配格式“ x-xxxxxxxx”,即始终以1- [8个字符长度]混合az 0-9,并省略其他所有内容

[root@centos64 ~]# cat /tmp/out| sed s/x-xxxxxxxx/
i-b7a82af5
i-9d78f4df
i-92ea58d0
i-fa4acab8

I know this is basic, but I can only find examples of text substitution. 我知道这是基本的,但是我只能找到文本替换的示例。

grep -Eo '[a-z0-9]-[a-z0-9]{8}' file

The -E option makes it recognize extended regular expressions, so it can use {8} to match 8 repetitions. -E选项可以识别扩展的正则表达式,因此可以使用{8}来匹配8个重复。

The -o option makes it only print the part of the line that matches the regexp. -o选项使它仅打印与正则表达式匹配的行的一部分。

Why not just print whatever's between the quotes: 为什么不只打印引号之间的内容:

$ sed -n 's/[^"]*"\([^"]*\).*/\1/p' file
i-b7a82af5
i-9d78f4df
i-92ea58d0
i-fa4acab8

$ awk -F\" 'NF>1{print $2}' file                     
i-b7a82af5
i-9d78f4df
i-92ea58d0
i-fa4acab8

Through GNU sed, 通过GNU sed,

$ sed -nr 's/.*([a-z0-9]-[a-z0-9]{8}).*/\1/p' file
i-b7a82af5
i-9d78f4df
i-92ea58d0
i-fa4acab8

I think this is all you need: [0-9a-zA-Z]-[0-9a-zA-Z]{8} . 我认为这就是您所需要的: [0-9a-zA-Z]-[0-9a-zA-Z]{8} Try it out here . 在这里尝试。

这应该可以工作^[a-z0-9]-[a-zA-Z0-9]{8}$

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

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