Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match string (with regular expression) that begins with a string

Tags:

regex

linux

bash

In a bash script I have to match strings that begin with exactly 3 times with the string lo; so lololoba is good, loloba is bad, lololololoba is good, balololo is bad.

I tried with this pattern: "^$str1/{$n,}" but it doesn't work, how can I do it?

EDIT:

According to OPs comment, lololololoba is bad now.

like image 311
Jaeger Avatar asked Jul 07 '15 14:07

Jaeger


2 Answers

This should work:

pat="^(lo){3}"
s="lolololoba"
[[ $s =~ $pat ]] && echo good || echo bad

EDIT (As per OPs comment):

If you want to match exactly 3 times (i.e lolololoba and such should be unmatched):

change the pat="^(lo){3}" to:

pat="^(lo){3}(l[^o]|[^l].)"
like image 67
Jahid Avatar answered Oct 08 '22 15:10

Jahid


You can use following regex :

^(lo){3}.*$

Instead of lo you can put your variable.

See demo https://regex101.com/r/sI8zQ6/1

like image 21
Mazdak Avatar answered Oct 08 '22 16:10

Mazdak