Regex to match only first occurence with grep

Hello to all,

How would be the correct regex to match only the first occurence of
the pattern 3.*6.

I'm trying with 3.*6 trying to match only 34rrte56, but with my current regex is matching 4rrte567890123456789123powiluur56. And if I try with ?
doesn't print anything

echo "1234rrte567890123456789123powiluur56789" | grep --color -e '3.*6'
1234rrte567890123456789123powiluur56789

Thanks in advance for any help.

You can use a non-greedy expression to match only things between 3 and 6, but I can't see a way in grep to match only the first occurrence.

$ echo "1234rrte567890123456789123powiluur56789" | grep --color -m1 '3[^6]*6'
1234rrte567890123456789123powiluur56789

I probably wouldn't recommend this if the string is likely to contain formatting instructions:

$ printf "$(echo 1234rrte567890123456789123powiluur56789 | sed "s/3[^6]*6/\\\e[1;31m&\\\e[0m/")\n"
1234rrte567890123456789123powiluur56789

Hello Scott,

Thanks for your help. I want to do it in grep because I need to extract the matched strings using grep -o.

Actually, for the first example, I want to match only things that are between 3 and 6. That would be fine, not needed to match
only the first occurrence.

But for this new string, I want to match only the pattern 347 + something + 35 + 4 characters. And
After the patterns always follow 6789. But with the regex I'm trying is not printing anything.

echo "1234725493512216789012523475700354912350214678902002" | grep --color -e '347[^67]*35.{4}'

The match strings should be those 2 in red:

123472549351221678971252347570035491235021467890200

Maybe could be done with grep this.

Thanks in advance.

I tried

echo "12347254935122167890125234757003678912350214678902002" | grep -E '347[^67]*35.{4}'

and got the result as

12347254935122167890125234757003678912350214678902002

Hello krishmaths,

Thankss for the help.

It works for the first occurrence, but I realized that actually I need to match all
occurrences but separated as follow:

123472549351221678971252347570035491235021467890200

and not like this:

123472549351221678971252347570035491235021467890200

Do you think is possible with grep?

Thanks again.

It is not directly possible with grep because it matches regular expressions line by line.

If you can break the line into multiple lines, say by inserting a newline after this pattern is found, then you can use grep to extract all the matches.

I see that have the patterns in same line generate issues.

Do you know if it is possible to adapt the same regex to grep but directly from binary file?

Thanks again.