Hello! As a student, you were given a task in which you cannot use the pattern method built into java and you want to create your own regular expression handler. The task is: Parser, using simple regular expressions entered from the keyboard, containing control structures. - any character, * - 0 or more characters, + - 1 or more characters (a regular expression and a string are entered, the result is the position from which this expression occurs in the text)

Matcher for text search can be used. I would be happy to see links on the subject of creating my own regular expression handler.

  • on the speed of the work there? and brackets just will not? - pavel
  • @pavel there are no restrictions, except that the essence of the whole task is unit testing, but the speed of passage is not critical there. Bracket will not be. - Oleg Linkov
  • Can you use the example with + and * here they are associated with a symbol or by themselves? - pavel
  • @pavel they are associated with a symbol. colou * r color, color, colouur, etc. colou + r - color, colouur, etc. (but not color) - Linkov Oleg

1 answer 1

Very well-known implementation of such a search. For your task, you can even remove a number of checks. If you need a +, then replace it simply with the previous character and an asterisk. a+ -> aa* Code in C ++ but easily transferred to Java (only indexing in the string is used).

 // Формат регулярного выражения. // c Соответсвует любой букве "с" // .(точка) Соответсвует любому одному символу // ^ Соответсвует началу входящей строки // $ Соответствует концу входящей строки // * Соответствует появлению предыдущего символа от нуля до // нескольких раз int matchhere(char *regexp, char *text); int matchstar(int c, char *regexp, char *text); // match: поиск соответствий регулярному выражению по всему тексту int match(char *regexp, char *text) { char * save = text; if (regexp[0] == '^') return matchhere(regexp+1, text); do { /* нужно посмотреть даже пустую строку */ if (matchhere(regexp, text)) return text - save; } while (*text++ != '\0'); return -1; } // matchhere: поиск соответствий регулярному выражению в начале текста int matchhere(char *regexp, char *text) { if (regexp[0] == '\0') return 1; if (regexp[1] == '*') return matchstar(regexp[0], regexp+2, text); if (regexp[0] == '$' && regexp[1] == '\0') return *text == '\0'; if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text)) return matchhere(regexp+1, text+1); return 0; } // matchstar: поиск регулярного выражения вида с* с начала текста int matchstar(int c, char *regexp, char *text) { do { /* символ * соответствует нулю или большему количеству появлений */ if (matchhere(regexp, text)) return 1; } while (*text != '\0' && (*text++ == c || c == '.')); return 0; } 

The code is not mine, so the answer is general.