rregsub.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include "regexp.h"
  12. /* substitute into one string using the matches from the last regexec() */
  13. extern void
  14. rregsub(Rune *sp, /* source string */
  15. Rune *dp, /* destination string */
  16. int dlen,
  17. Resub *mp, /* subexpression elements */
  18. int ms) /* number of elements pointed to by mp */
  19. {
  20. Rune *ssp, *ep;
  21. int i;
  22. ep = dp+(dlen/sizeof(Rune))-1;
  23. while(*sp != '\0'){
  24. if(*sp == '\\'){
  25. switch(*++sp){
  26. case '0':
  27. case '1':
  28. case '2':
  29. case '3':
  30. case '4':
  31. case '5':
  32. case '6':
  33. case '7':
  34. case '8':
  35. case '9':
  36. i = *sp-'0';
  37. if(mp[i].rsp != 0 && mp!=0 && ms>i)
  38. for(ssp = mp[i].rsp;
  39. ssp < mp[i].rep;
  40. ssp++)
  41. if(dp < ep)
  42. *dp++ = *ssp;
  43. break;
  44. case '\\':
  45. if(dp < ep)
  46. *dp++ = '\\';
  47. break;
  48. case '\0':
  49. sp--;
  50. break;
  51. default:
  52. if(dp < ep)
  53. *dp++ = *sp;
  54. break;
  55. }
  56. }else if(*sp == '&'){
  57. if(mp[0].rsp != 0 && mp!=0 && ms>0)
  58. if(mp[0].rsp != 0)
  59. for(ssp = mp[0].rsp;
  60. ssp < mp[0].rep; ssp++)
  61. if(dp < ep)
  62. *dp++ = *ssp;
  63. }else{
  64. if(dp < ep)
  65. *dp++ = *sp;
  66. }
  67. sp++;
  68. }
  69. *dp = '\0';
  70. }