Jaeger
Jaeger

Reputation: 371

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

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.

Upvotes: 5

Views: 378

Answers (4)

Jahid
Jahid

Reputation: 22438

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].)"

Upvotes: 6

Mitch
Mitch

Reputation: 1644

As per your comment:

... more than 3 is bad so "lolololoba" is not good! 

You'll find that @Jahid's answer doesn't fit (as his gives you "good" to that test string.

To use his answer with the correct regex:

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

This verifies that there are three "lo"s at the beginning, and not another one immediately following the three.

Note that if you're using bash you'll have to escape that ! in the first line (which is what my regex above does)

Upvotes: 0

anubhava
anubhava

Reputation: 786011

You can use this awk to match exactly 3 occurrences of lo at the beginning:

# input file
cat file
lololoba
balololo
loloba
lololololoba
lololo

# awk command to print only valid lines
awk -F '^(lo){3}' 'NF == 2 && !($2 ~ /^lo/)' file
lololoba
lololo

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107347

You can use following regex :

^(lo){3}.*$

Instead of lo you can put your variable.

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

Upvotes: 3

Related Questions