regex/ string/ bash/ math

I have a kind of complicated string, the form is

"xxxp+NUMyyy"

where xxx, NUM, and yyy are all variable length, and '+' can be a mathematical operator, such as '-', '*', '/', or '='.

I am trying to figure out the best way to get what mathematical operator and number the user has entered.

I tried using combination of things like this:

    echo `expr match "tcp+111" '\([+-=*/]\)'`
    echo `expr match "tcp+111" '\(\+\-=\*/\)'`

Nothing has worked thus far. I'm thinking the easiest way to do such a thing is by using regular expressions, but maybe I'm wrong? What is a good way to do this?

Thank You.

example input: "tcjp-100" "p+1" "p+1:debug" "cp=11:v". I did forget to mention, before the operator there will always be the letter 'p'. In addition, 'xxx' and 'yyy' do not have to be present, but can be

You can use Bash's regex matching feature.

string="xxxp+3456yyy"
pattern="[^*/+-]*([*/+-]*)([[:digit:]]+).*"    # the hyphen must come last (or first, but after ^) in the character sets

[[ $string =~ $pattern ]]
echo "${BASH_REMATCH[1]}"    # operator
echo "${BASH_REMATCH[2]}"    # number

暂无
暂无

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question R - string manipulation and extraction Bash string manipulation regex or string indexing bash string manipulation using sed/regex Bash: String manipulation with sed and Regular expression is not working: replace a string by slash Perl regex & data extraction/manipulation Text manipulation within a dataframe: words extraction Regex string extraction Translation string extraction String Extraction using regexp String “Slot-Extraction”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM