How to extract the substring between two markers?

前端 未结 18 2336
慢半拍i
慢半拍i 2020-11-22 06:02

Let\'s say I have a string \'gfgfdAAA1234ZZZuijjk\' and I want to extract just the \'1234\' part.

I only know what will be the few characte

18条回答
  •  孤街浪徒
    2020-11-22 06:13

    Typescript. Gets string in between two other strings.

    Searches shortest string between prefixes and postfixes

    prefixes - string / array of strings / null (means search from the start).

    postfixes - string / array of strings / null (means search until the end).

    public getStringInBetween(str: string, prefixes: string | string[] | null,
                              postfixes: string | string[] | null): string {
    
        if (typeof prefixes === 'string') {
            prefixes = [prefixes];
        }
    
        if (typeof postfixes === 'string') {
            postfixes = [postfixes];
        }
    
        if (!str || str.length < 1) {
            throw new Error(str + ' should contain ' + prefixes);
        }
    
        let start = prefixes === null ? { pos: 0, sub: '' } : this.indexOf(str, prefixes);
        const end = postfixes === null ? { pos: str.length, sub: '' } : this.indexOf(str, postfixes, start.pos + start.sub.length);
    
        let value = str.substring(start.pos + start.sub.length, end.pos);
        if (!value || value.length < 1) {
            throw new Error(str + ' should contain string in between ' + prefixes + ' and ' + postfixes);
        }
    
        while (true) {
            try {
                start = this.indexOf(value, prefixes);
            } catch (e) {
                break;
            }
            value = value.substring(start.pos + start.sub.length);
            if (!value || value.length < 1) {
                throw new Error(str + ' should contain string in between ' + prefixes + ' and ' + postfixes);
            }
        }
    
        return value;
    }
    

提交回复
热议问题