简体   繁体   English

正则表达式匹配bash中的字符串

[英]Regex match strings in bash

I was curious if you can make regex to match 2nd character of a string with 2 from the back? 我很好奇您是否可以让正则表达式将字符串的第二个字符与后面的2匹配? For 1st and last its pretty easy and straightforward but i was curious if it can be done for any str length? 对于第一个也是最后一个,它非常容易和直接,但是我很好奇它是否可以在任何str长度上完成? I was playing with it in bash for the last hour and none of my solutions seams to work. 在过去的一个小时中,我一直在用bash玩游戏,但我的解决方案都无法正常工作。

^(.).*\\1$ thats the regex I have for 1st and last char it probably needs too be a little edited for this but i have no idea how. ^(.).*\\1$多数民众赞成在正则表达式我为第一个和最后一个字符,它可能也需要对此进行一点编辑,但我不知道如何。

Can you help me with the other one? 你能帮我另一个吗?

examples:
abcsba - match as b(index 1) == b(index -2)
regex - match as e(index 1) == a(index -2)
abba - match 
unix - not matcha as indexOf(n) != indexOf(i)
linux - not match as indexOf(i) != indexOf(u)

Just discard equal number of character from the beginning and from the end: 只需从头到尾丢弃相等数量的字符即可:

$ pat='^.(.).*\1.$'
$ [[ abcsba =~ $pat ]] && echo yes || echo no
yes
$ [[ unix =~ $pat ]] && echo yes || echo no
no

or, generally use {n} (eg. to match 3rd character with 3rd from the end): 或者,通常使用{n} (例如,将第3个字符与末尾的第3个字符匹配):

pat='^.{2}(.).*\1.{2}$'
$ [[ abcdef =~ $pat ]] && echo yes || echo no
no
$ [[ abccef =~ $pat ]] && echo yes || echo no
yes

In the second example we use single-character-ERE duplication operator {m,n} defined in POSIX for both basic and extended regular expressions (ERE variant is only relevant here though, since =~ operator in bash uses ERE). 在第二个示例中,我们使用在POSIX中定义的单字符-ERE 复制运算符{m,n}来表示基本正则表达式和扩展正则表达式(不过,ERE变体仅在此处相关,因为bash =~运算符使用ERE)。 The {n} form is a special case, equal to {n,n} , meaning repeat the preceding character (or group) exactly n times. {n}形式是一种特殊情况,等于{n,n} ,表示正好重复前一个字符(或组) n次。

As i understood you want to extract the characters . 据我了解,您想提取字符。 You can do it by awk command 你可以通过awk命令来做到

echo "praveen" | 回声“ praveen” | awk '{print substr($1,1,2)}' pr 01HW497089:tmp Controller$ awk'{print substr($ 1,1,2)}'pr 01HW497089:tmp控制器$

Here i am extracting column1 value from character 1 to character 3 我在这里从字符1到字符3提取column1的值

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

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