2 * ##/%% variable matching code ripped out of ash shell for code sharing
4 * This code is derived from software contributed to Berkeley by
7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9 * Copyright (c) 1989, 1991, 1993, 1994
10 * The Regents of the University of California. All rights reserved.
12 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
13 * was re-ported from NetBSD and debianized.
21 # define FAST_FUNC /* nothing */
22 # define PUSH_AND_SET_FUNCTION_VISIBILITY_TO_HIDDEN /* nothing */
23 # define POP_SAVED_FUNCTION_VISIBILITY /* nothing */
30 char* FAST_FUNC scan_and_match(char *string, const char *pattern, unsigned flags)
34 unsigned len = strlen(string);
37 /* We can stop the scan early only if the string part
38 * we are matching against is shrinking, and the pattern has
39 * an unquoted "star" at the corresponding end. There are two cases.
41 * "qwerty" does not match against pattern "*zy",
42 * no point in trying to match "werty", "erty" etc:
44 early_exit = (flags == (SCAN_MOVE_FROM_LEFT + SCAN_MATCH_RIGHT_HALF) && pattern[0] == '*');
46 if (flags & SCAN_MOVE_FROM_LEFT) {
48 end = string + len + 1;
52 if (flags == (SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF)) {
54 * "qwerty" does not match against pattern "qz*",
55 * no point in trying to match "qwert", "qwer" etc:
57 const char *p = pattern + strlen(pattern);
58 if (--p >= pattern && *p == '*') {
60 while (--p >= pattern && *p == '\\')
71 if (flags & SCAN_MATCH_LEFT_HALF) {
73 r = fnmatch(pattern, string, 0);
76 r = fnmatch(pattern, loc, 0);
78 if (r == 0) /* match found */
82 printf("(early exit) ");
87 if (flags & SCAN_MOVE_FROM_LEFT) {
97 int main(int argc, char *argv[])
104 setvbuf(stdout, NULL, _IONBF, 0);
108 "Usage: match <test> [test...]\n\n"
109 "Where a <test> is the form: <string><op><match>\n"
110 "This is to test the shell ${var#val} expression type.\n\n"
111 "e.g. `match 'abc#a*'` -> bc"
121 off = strcspn(string, "#%");
123 printf("invalid format\n");
127 scan_flags = pick_scan(op[0], op[1]);
129 printf("'%s': flags:%x, ", string, scan_flags);
135 loc = scan_and_match(string, pattern, scan_flags);
137 if (scan_flags & SCAN_MATCH_LEFT_HALF) {
138 printf("'%s'\n", loc);
142 printf("'%s'\n", string);