How to find the string which is starting with some leters and having numbers from 4th position?

How to find the string which is starting with ROS and having numbers from 4th position
For example: I have strings as below

string1 :ROSE543
string2 :ROS543
string3 :ROS54SQD
string4 :ROSEFLOWER
string5 :FLOWERROSE

here i have to know the string starts with ROS and from 4th position to till the end (n numbers) it having only numbers.
Note: these strings will be passed as a variable and i'm using ksh.

Result should be: ROS543 (because it is starting with ROS and from 4th position to end having only numbers)

Can someone help me to get this result?
Thanks in advance!!!

What ksh version do you have?

man ksh93 :

Try

[[ $string2 =~ ROS[0-9]*$ ]] && echo OK || echo NOK
OK

Of course it is

[[ $string2 =~ ROS[0-9]+$ ]] && echo OK || echo NOK

Minimum one digit.

1 Like

Thanks for the answer :slight_smile:

I tried the below code and got error.
CODE :

a=sss2345
set -x
if [[ ( $a =~ sss[0-9]*$ ) ]]; then
echo "4th position is num"
else
echo "4th position is not num"
fi

ERROR : Syntax error at line 3 : `=~' is not expected.

ERROR:
Syntax error at line 3 : `=~' is not expected.

Looks like your shell version doesn't provide that construct. What is it?

Obviously ksh88 - that knows [[ ]] but not its =~ operator.
Is it possible to use bash instead?

In ksh88 (and bash) you can emulate

f [[ ( $a =~ sss[0-9]*$ ) ]]

with

if [[ $a == *sss* ]] && [[ ${a##*sss} != *[!0-9]* ]]

And

f [[ ( $a =~ ^sss[0-9]*$ ) ]]

with

if [[ $a == sss* ]] && [[ ${a#sss} != *[!0-9]* ]]
1 Like