Freddiboy
Freddiboy

Reputation: 133

Trim a string between two delimiters

I have a number string, for example 14569927-4332-119-02. I would like to trim this from the first '-' delimiter to the next '-' delimiter. The result let be only: '4332'.

I tried this regex: (^-[0-9]) but I it's not perfect.

How could I trim this '4332' from the string?

Thank you & have a nice weekend!

Upvotes: 3

Views: 2311

Answers (3)

Tom Burger
Tom Burger

Reputation: 667

Talking about SAP and ABAP, using regex is not probably the best option - it might provide good sign of mastery for writer, but it makes the stuff no easy for readers. In ABAP you might probably resort to other options...

This would be my take:

data: l_var type string value '14569927-4332-119-02',
      lt_parts type standard table of string,
      l_result type string.

split l_var at '-' into table lt_parts.
read table lt_parts into l_result index 2.
if sy-subrc ne 0.
  " error handling --- not found...
endif.

Effectively these are two lines instead of one regex, but it is much more transparent what you are doing...

Upvotes: 2

jaypal singh
jaypal singh

Reputation: 77095

A few options...

awk:

$ string='14569927-4332-119-02'
$ awk -F- '{print $2}' <<< "$string"
4332

bash:

$ string=${string%-*-*}
$ string=${string#*-}
$ echo "$string"
4332

cut:

$ cut -d'-' -f2 <<< "$string"
4332

Upvotes: 1

user529758
user529758

Reputation:

Try using sed:

$ echo "14569927-4332-119-02" | sed 's/[^\-]*\-\([^\-]*\)\-.*/\1/g'
4332

Upvotes: 0

Related Questions