I have a string that contains a timestamp and some random characters. For example, str = "11:05:46 some random text here"
and I just want to grab the timestamp and store it in a variable using regex.
The regex for the timestamp format is
\d{2}:\d{2}:\d{2}
and I am using regexp on Matlab like this:
timestamp = regexp(str,expression)
where str is "11:05:46 some random text here"
and expression is '\d{2}:\d{2}:\d{2}'
but it is returning the index (1) and not the value itself (11:05:46
).
Is there a way on Matlab that I can get the value and store it in a variable when the value matches a regex expression? expected output: 11:05:46
Or is there a way where I can just match everything else but the timestamp? expected output: some random text here
You need to pass 'match'
as the 3rd argument to the regexp
function:
timestamp = regexp(str,expression, 'match')
Output:
timestamp =
{
[1,1] = 11:05:46
}
The 'match'
argument makes Matlab output text of each substring that matches the pattern in expression, see documenation.
Using regexprep
you may remove the timestamp at the start of the string to return all that remains:
>> regexprep(str,expression,'')
ans = some random text here