Returning negetive numbesr from text file using regexp
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi! I'm writing code that takes a text file containing three seperate variables of numbers, time, x-displacement and y-displacement.
The three variables are all surounded by unique spacers like '&&*' and ',,,*' I've used fileread and regexp to read the file and put all numbers into an array, only issue is that they all become possitive, when some of the y-displacement values need to be negetive.
experiment = ('(?<=*[^0-9]*)[0-9]*\.?[0-9]+');
inputText = str2double(regexp(dataFile,experiment, 'match'))
Thanks for any help
Jack
댓글 수: 0
채택된 답변
Johannes Fischer
2019년 9월 19일
With questions like these it's very helpful to have an example of waht exactly your data looks like. If you know exactly how your spacers look like, you could also try strsplit (https://www.mathworks.com/help/matlab/ref/strsplit.html?searchHighlight=strsplit&s_tid=doc_srchtitle) which can detect multiple delimiters.
If you want to use regular expressions, add '\-' in yout brackets, to also match the minus-sign
(?<=[^0-9])([0-9\-]*)\.*([0-9\-]+)
I tested it with &&-1234...-4562 here https://regex101.com/, which gave me an error for the '*' inside the lookbehind.
str = '&&-1234...4562';
vals = cell2mat(cellfun(@str2double, regexp(str,'(?<=[^0-9])([0-9\-]*)\.*([0-9\-]+)', 'tokens'), 'UniformOutput', false))
댓글 수: 2
Johannes Fischer
2019년 9월 23일
편집: Johannes Fischer
2019년 9월 23일
Depending on how your code is used or shared and how permanent this style of data saving is (it looks a bit 'unusual' i have to say), you might want to use strsplit in this case. That would make your code much more readable for somebody not familiar with regexp and if your delimiters would never change or only slightly, debugging would be easier. I cannot tell you however which way is faster. This is how it could work
a = '&&*0.0000&&,,* 5.6054*,* -1.1018&*,,,&';
substr = strsplit(a, {'&&*', '&&,,*\t', '*,*\t', '&*,,,&'});
data = cellfun(@str2double, substr(2:4));
The '\t' represent the tab-stops that seem to be present in your delimiters, but they are not necessary, as str2double just ignores them.
If this code is just for you and you dont want your regexp skills to get rusty, go for it :)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 String Parsing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!