In Emacs I'm manipulating some pipe separated data and I'd like to build some validation functions. The first function I would like is to ensure that I have the proper number of fields. In this example, I have four columns of data. At this point I want a warning for the second and forth lines because there aren't at least three separators (|).
1|2|3|4 one|two| four|five|6|7 abc||
To count the number of pipe characters in the current line, try this:
(count-matches "|" (point-at-bol) (point-at-eol))
To validate the whole buffer, consider this function:
(require 'cl)
(defun invalid-points ()
(save-excursion
(goto-char (point-min))
(loop while (re-search-forward ".$" nil t)
unless (= 3 (count-matches "|" (point-at-bol) (point-at-eol)))
collect (point))))
which would return a list of positions of lines that contain invalid number of fields (so, would return nil only when the whole buffer were valid).
For interactive use, perhaps the easiest way is to abuse the font-lock-mode to highlight the invalid lines (or vice versa):
(font-lock-add-keywords
nil '(("^[^|\n]*\\(|[^|\n]*\\)\\{3\\}$" 0 highlight)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With