Extract string between any two Alphanumaric strings

Note: Subject line correction --> any two Alphanumaric strings = any two strings

I am trying to come-up with geneic code, that can give a string between any two given strings in a given line(first occurance). Here input text line can have control characters.

Below code works as long as search strings do not have control characters. I know why this is failing,, but I need code that can handle special characters and reusable, Even if it means writing a function with multiple lines of code. But Love to see if that can be done in a single line.!!

How can we do that in ksh/bash/perl?

 
test.sh
# get a string between two AlphaNumeric character strings. 
v1='aa'; v2='cc'
echo "aaaabbbbbccccc" | sed -e "s/.*${v1}//;s/${v2}.*//"
 
# This works as long as two search strings do not have special chacters.
$> test.sh   
bbbbb
 
# This fails due to control characters in sed command. 
test.sh 
# Get string between any two search strings from input line.
v1='$?'; v2='cc'
echo "aa$?bbbbbccccc" | sed -e "s/.*${v1}//;s/${v2}.*//"
 
$> test.sh
aa0bbbbb

Did you try this?

v1='\$\?'

I am not trying to do this for a known fixed search string,,
I need code that can handle search strings ${v1}, ${v2} with special characters. I can do this using advanced languages like Java.
Does sed or awk have any magic that can handle it in a one line command!.

is it not the initial evaluation on your echo causing the issue:


#   echo "aa$?bbbbbccccc"
aa0bbbbbccccc

#   echo "aa\$?bbbbbccccc"
aa$?bbbbbccccc

or
#   echo 'aa$?bbbbbccccc'
aa$?bbbbbccccc

allows:
#   echo 'aa$?bbbbbccccc'  | sed -e "s/.*${v1}//;s/${v2}.*//"
bbbbb


Thanks Tytalus, as long as I have my search strings and input string in single quotes, it works..

Following input string has two matching occurances 1. bbbb 2. dddd. Why sed prints last occurance of matched string?

How can I control which matched string gets printed. Say I want to print only first occurance or both matched strings seperated by something(comma!)?

$> v1='$?'; v2='cc'; echo 'aa$?bbbbccccc$?ddddccc' | sed -e "s/.*${v1}//;s/${v2}.*//"
 
dddd