rpmatch.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* Determine whether string value is affirmation or negative response
  2. according to current locale's data.
  3. This file is part of the GNU C Library.
  4. Copyright (C) 1996-2019 Free Software Foundation, Inc.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, see
  15. <http://www.gnu.org/licenses/>. */
  16. #include <langinfo.h>
  17. #include <stdlib.h>
  18. #include <regex.h>
  19. /* Match against one of the response patterns, compiling the pattern
  20. first if necessary. */
  21. static int
  22. try (const char *response,
  23. const int tag, const int match, const int nomatch,
  24. const char **lastp, regex_t *re)
  25. {
  26. const char *pattern = nl_langinfo (tag);
  27. if (pattern != *lastp)
  28. {
  29. /* The pattern has changed. */
  30. if (*lastp != NULL)
  31. {
  32. /* Free the old compiled pattern. */
  33. __regfree (re);
  34. *lastp = NULL;
  35. }
  36. /* Compile the pattern and cache it for future runs. */
  37. if (__regcomp (re, pattern, REG_EXTENDED) != 0)
  38. return -1;
  39. *lastp = pattern;
  40. }
  41. /* Try the pattern. */
  42. return __regexec (re, response, 0, NULL, 0) == 0 ? match : nomatch;
  43. }
  44. int
  45. rpmatch (const char *response)
  46. {
  47. /* We cache the response patterns and compiled regexps here. */
  48. static const char *yesexpr, *noexpr;
  49. static regex_t yesre, nore;
  50. return (try (response, YESEXPR, 1, 0, &yesexpr, &yesre) ?:
  51. try (response, NOEXPR, 0, -1, &noexpr, &nore));
  52. }