Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract characters at a set position

Tags:

string

r

truncate

I am trying to find a function that will extract characters at a certain position within a string. For example, I have a long file name with a date in it, and I want to end up with only the date:

'LT50420331984221PAC00_B7.tif'

and I want only the '1984221' portion. I've come up with a complicated function, but was wondering if there is a more elegant solution.

like image 400
user2632308 Avatar asked Jul 30 '13 01:07

user2632308


People also ask

How do I extract a specific part of a string in Python?

You can extract a substring from a string before a specific character using the rpartition() method. rpartition() method partitions the given string based on the last occurrence of the delimiter and it generates tuples that contain three elements where.

Which function extracts characters from the first position of a string?

The SUBSTR( ) function returns characters from the string value starting at the character position specified by start.

How do I extract part of a string in R?

The substring function in R can be used either to extract parts of character strings, or to change the values of parts of character strings. substring of a vector or column in R can be extracted using substr() function. To extract the substring of the column in R we use functions like substr() and substring().

How do I extract a string between two delimiters in Python?

Create a regular expression to extract the string between two delimiters as regex = “\\[(. *?) \\]” and match the given string with the Regular Expression. Print the subsequence formed.


2 Answers

If you know the exact position of the date in your string you can use

substr('LT50420331984221PAC00_B7.tif', 10, 16)
like image 168
alko989 Avatar answered Oct 07 '22 00:10

alko989


For example:

gsub('(.*)([0-9]+{7})[A-Z].*','\\2','LT50420331984221PAC00_B7.tif')
"1984221"

Here I assume that the date is 7 digits before a capital letter.

like image 29
agstudy Avatar answered Oct 07 '22 00:10

agstudy