&nb...">

Optional Regular Expression Elements

If I have this regex

print_first = print_first.replace(/ T(op Choice)?/gi, "<span class='top_choice'>&nbsp;Top Choice</span>");

Shouldn't this match these lines: T, To, Top, Top C, Top Ch, Top Cho, Top Choi, Top Choic, Top Choice?

What would be the best way to do this?

+4
source share
2 answers

The whole group becomes optional, but it is all or nothing is a symbol. That way your regex will match the strings ' T'or ' Top Choice'.

Unfortunately, the regex for getting this kind of behavior is pretty ugly in nature. You will need a bunch of nested optional groups, something like the following:

/ T(o(p( (C(h(o(i(ce?)?)?)?)?)?)?)?)?/gi

, , |. , , , , , , , :

/ Top Choice?| Top Choi?| Top Ch?| Top ?| To?/gi

, ' Top Choice' ' Top Choic', ' Top Choi' ' Top Cho' .. , , .

+5

Regex. , .

String r = "TopChoice";
while (r.length() > 0) {
    //Check for match to String r
    r = r.substring(0, r.length() - 1).trim();
}
0

Source: https://habr.com/ru/post/1537741/


All Articles