[go: up one dir, main page]

Menu

[r1]: / strregtok.c  Maximize  Restore  History

Download this file

81 lines (73 with data), 2.5 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* strregtok.c: Implementation of regexp seperated string tokenizer.
*
* This file is part of tabler.
* Copyright (C) 2007 Heath Caldwell
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License , or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* The Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111 USA
*
* You may contact the author by:
* e-mail: Heath Caldwell <hncaldwell@csupomona.edu>
*/
#include <stdlib.h>
#include <stdio.h>
#include <regex.h>
#include "conf.h"
#include "strregtok.h"
/* strregtok
*
* Breaks a string up into tokens seperated by a regex seperator.
* Works just like strtok but you use a regex_t for the seperator
* instead of a string of single character delimiters.
*
* Takes: string: Pointer to the string to be tokenized.
* NOTE: This string will get clobbered.
* seperator: regex_t of a compiled regex to use
* as the seperator.
*
* Returns: Pointer to next token or null if there are no more.
* See documenation for strtok.
*
* Internal Variables:
* _strregtok_previous_end: Stores end of previous token.
*/
char *
strregtok(char *string, const regex_t *seperator)
{
char error_string[ERROR_STRING_LENGTH];
regmatch_t match[1]; /* To store the matching part. */
int error = 0;
/* Return zero for the call after the last token. */
if(!string && !_strregtok_previous_end) return 0;
if(string)
_strregtok_previous_end = string;
else
string = _strregtok_previous_end;
error = regexec(seperator, string, 1, match, 0);
if(!error) {
_strregtok_previous_end = string + match[0].rm_eo;
*(string + match[0].rm_so) = '\0';
return string;
} else if(error == REG_NOMATCH) {
/* This is the last token. */
_strregtok_previous_end = 0;
return string;
} else {
regerror(error, seperator, error_string, ERROR_STRING_LENGTH);
fprintf(stderr, "Error: %s\n", error_string);
exit(EXIT_FAILURE);
}
}