regexes for parsing formatted numbers

后端 未结 3 1534
后悔当初
后悔当初 2021-01-22 13:00

I am parsing documents which contain large amounts of formatted numbers, an example being:

 Frc consts  --     1.4362                 1.4362                 5.41         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-22 13:31

    As I understand it, each line comprises one or more fixed-width fields, which may contain labels, spaces, or data of different kinds. If you know the widths and types of the fields, extracting their data is a simple matter of substring(), trim() and (optionally) Whatever.parseWhatever(). Regexes can't make that job any easier--in fact, all they can do is make it a lot harder.

    Scanner doesn't really help, either. True, it has predefined regexes for various value types, and it does the conversions for you, but it still needs to be told which type to look for each time, and it needs the fields to be separated by a delimiter it can recognize. Fixed-width data doesn't require delimiters, by definition. You might be able to fake the delimiters by doing a lookahead for however many characters should be left in the line, but that's just another way of making the job harder than it needs to be.

    It sounds like performance is going to be a major concern; even if you could make a regex solution work, it would probably be too slow. Not because regexes are inherently slow, but because of the contortions you would have to go through to make them fit the problem. I suggest you forget about regexes for this job.

提交回复
热议问题