C# Find String between matching brace

Date: 2021-04-28
public static string FindStringBetweenMatchingBrace(string s, int start, char startBrace, char endBrace)
{
    var braces = new char[] { startBrace, endBrace };
    var pos = start;
    var end = start;
    var level = 0;
    var notStarted = true;
    while (true)
    {
        var index = s.IndexOfAny(braces, pos);
        if (index < 0) break;
        if (notStarted)
        {
            notStarted = false;
            start = index + 1;
        }
        if (s[index] == startBrace) level++;
        if (s[index] == endBrace) level--;
        if (level <= 0)
        {
            end = index;
            break;
        }
        pos = index + 1;
    }
    return s.Substring(start, end - start);
}
function indexOfAny(str, anyOf, startIndex) {
    if (!str) return -1;
    if (!anyOf) return -1;
    let minIndex = -1;
    for (let j = 0; j < anyOf.length; j++) {
        let index = str.indexOf(anyOf[j], startIndex);
        if (index >= 0 && (minIndex === -1 || index < minIndex)) {
            minIndex = index;
        }
    }
    return minIndex;
};

function findStringBetweenMatchingBrace(s, start, startBrace, endBrace) {
    const braces = [startBrace, endBrace];
    let pos = start;
    let end = start;
    let level = 0;
    let notStarted = true;
    while (true) {
        var index = indexOfAny(s, braces, pos);
        if (index < 0) break;
        if (notStarted) {
            notStarted = false;
            start = index + 1;
        }
        if (s[index] == startBrace) level++;
        if (s[index] == endBrace) level--;
        if (level <= 0) {
            end = index;
            break;
        }
        pos = index + 1;
    }
    return s.substring(start, end);
}


const result = findStringBetweenMatchingBrace("abc (def efg (abf ddd) t)est", 0, "(", ")");
console.log(result);
const result2 = findStringBetweenMatchingBrace(result, 0, "(", ")");
console.log(result2);
50230cookie-checkC# Find String between matching brace