自己一致正規表現[終了]


15

自分自身と一致する重要な正規表現を記述します。

たとえば#.*$、Pythonの文字列外のコメントは行末まで一致し、perlの正規表現構文でも一致します。

ルール

  • 正規表現は、有用または実用的な何かを行う必要があります。
  • 使用している正規表現構文を教えてください(perlやPOSIXなど)。
  • 勝者は、最高の投票に準拠した回答です。
  • クリエイティブに!

6
:SOの質問は、有効な正規表現にマッチする正規表現があるかどうか、しばらく前にあったstackoverflow.com/questions/172303/...
パトリックOscityは

5
自明ではないことを定義します。私は、OK、意味A些細なことだろうが、どこで線を引くのですか?また、「自己一致」とは、自分自身との一致することを意味しますか、それとも他の文字列と一致することを許可しますか?だろう.資格?
ミスターリスター

1
正規表現を記述する文法はコンテキストに依存しないため、実際には正規表現ではなかった@padde。
FUZxxl

1
@FUZxxlはい、それは本当ですが、他の正規表現と一致する正規表現を書くことはできますが、一致した正規表現の有効性は気にしません。
パトリックオスシティ

1
@paddeさて、無効な正規表現とは何ですか?無効な正規表現は明らかに正規表現ではありません。「はい、それは本当ですが、マッチした正規表現が本当に正規表現である場合は、1つは、まだ他の正規表現にマッチする正規表現を書きますが、doesntのケアでした」:あなたは、本質的に言うので(原文のまま!)
FUZxxl

回答:



11

パイソン

以下は自己一致正規表現ジェネレータです。正規表現がなければならないあなたは二つのリストを提供し、1は(自身のマッチングに加えて)正規表現が一致している必要がありますことを訓練データが含まれ、他の学習データが含まれていませ一致します:

from random import choice, randrange
import re
from itertools import zip_longest, chain, islice
from operator import itemgetter

CHAR_SET = [chr(i) for i in range(128)] + [r"\\", r"\d", r"\D",
                                           r"\w", r"\W", r"\s",
                                           r"\S", r"?:", r"\1",
                                           r"\2", r"\A", r"\b",
                                           r"\B", r"\Z", r"\.",
                                           r"\[", r"\]", r"\(",
                                           r"\)", r"\{", r"\}",
                                           r"\+", r"\|", r"\?",
                                           r"\*"]

CHAR_SAMPLE = []
BREAKPOINT = re.compile(
    r"""
    \(.*?\)|
    \[.*?\]|
    \{.*?\}|
    \w+(?=[\(\[\{])?|
    \S+?|
    \.\*\??|
    \.\+\??|
    \.\?\??|
    \\.|
    .*?
    """,
    re.VERBOSE)

MATCH_BRACKETS = {'(': ')', '[': ']', '{': '}'}
CLOSE_BRACKETS = {')', ']', '}'}
REGEX_SEEDER = [
    r".*?",
    r"(?:.*?)",
    r"\w|\s",
    r"(?<.*?)",
    r"(?=.*?)",
    r"(?!.*?)",
    r"(?<=.*?)",
    r"(?<!.*?)",
    ]

LEN_LIMIT = 100

def distribute(distribution):
    global CHAR_SAMPLE
    for item in CHAR_SET:
        if item in distribution:
            CHAR_SAMPLE.extend([item] * distribution[item])
        else:
            CHAR_SAMPLE.append(item)

def rand_index(seq, stop=None):
    if stop is None:
        stop = len(seq)
    try:
        return randrange(0, stop)
    except ValueError:
        return 0

def rand_slice(seq):
    try:
        start = randrange(0, len(seq))
        stop = randrange(start, len(seq))
        return slice(start, stop)
    except ValueError:
        return slice(0,  0)


#Mutation Functions

def replace(seq):
    seq[rand_index(seq)] = choice(CHAR_SAMPLE)

def delete(seq):
    del seq[rand_index(seq)]

def insert(seq):
    seq.insert(rand_index(seq, len(seq) + 1), choice(CHAR_SAMPLE))

def duplicate(seq):
    source = rand_slice(seq)
    seq[source.stop: source.stop] = seq[source]

def swap(seq):
    if len(seq) < 2: return
    a = rand_index(seq, len(seq) - 1)
    seq[a], seq[a + 1] = seq[a + 1], seq[a]

dummy = lambda seq: None

MUTATE = (
    replace,
    delete,
    insert,
    duplicate,
    swap,
    dummy,
    dummy,
    )

def repair_brackets(seq):
    """Attempts to lower the percentage of invalid regexes by
    matching orphaned brackets"""

    p_stack, new_seq = [], []
    for item in seq:
        if item in MATCH_BRACKETS:
            p_stack.append(item)
        elif item in CLOSE_BRACKETS:
            while p_stack and MATCH_BRACKETS[p_stack[-1]] != item:
                new_seq.append(MATCH_BRACKETS[p_stack[-1]])
                p_stack.pop()
            if not p_stack:
                continue
            else:
                p_stack.pop()
        new_seq.append(item)
    while p_stack:
        new_seq.append(MATCH_BRACKETS[p_stack.pop()])
    return new_seq

def compress(seq):
    new_seq = [seq[0]]
    last_match = seq[0]
    repeat = 1
    for item in islice(seq, 1, len(seq)):
        if item == last_match:
            repeat += 1
        else:
            if repeat > 1:
                new_seq.extend(list("{{{0}}}".format(repeat)))
            new_seq.append(item)
            last_match = item
            repeat = 1
    else:
        if repeat > 1:
            new_seq.extend(list("{{{0}}}".format(repeat)))
    return new_seq


def mutate(seq):
    """Random in-place mutation of sequence"""
    if len(seq) > LEN_LIMIT:
        seq[:] = seq[:LEN_LIMIT]
    c = choice(MUTATE)
    c(seq)

def crossover(seqA, seqB):
    """Recombination of two sequences at optimal breakpoints
    along each regex strand"""

    bpA = [item.start() for item in BREAKPOINT.finditer(''.join(seqA))]
    bpB = [item.start() for item in BREAKPOINT.finditer(''.join(seqA))]
    slObjA = (slice(*item) for item in zip(bpA, bpA[1:]))
    slObjB = (slice(*item) for item in zip(bpB, bpB[1:]))
    slices = zip_longest(
        (seqA[item] for item in slObjA),
        (seqB[item] for item in slObjB),
        fillvalue=[]
        )
    recombinant = (choice(item) for item in slices)
    return list(chain.from_iterable(recombinant))

#Fitness testing

def match_percentage(match):
    """Calculates the percentage a text actually matched
    by a regular expression"""

    if match and match.endpos:
        return (match.end() - match.start()) / match.endpos
    else:
        return 0.001

def fitness_test(seq, pos_matches, neg_matches):
    """Scoring algorithm to determine regex fitness"""

    try:
        self_str = ''.join(seq)
        regex = re.compile(self_str)
    except (re.error, IndexError):
        seq[:] = repair_brackets(seq)
        try:
            self_str = ''.join(seq)
            regex = re.compile(self_str)
        except (re.error, IndexError):
            return 0.001

    pos_score = sum(match_percentage(regex.search(item))
                    for item in pos_matches) / len(pos_matches) / 3

    neg_score = (1 - sum(match_percentage(regex.search(item))
                    for item in neg_matches) / len(neg_matches)) / 3

    self_score = match_percentage(regex.search(self_str)) / 3

    return pos_score + self_score + neg_score

#Population Management

def generate_pop(pos_matches, neg_matches, pop_size):
    sources = (pos_matches, REGEX_SEEDER)
    return [crossover(
        choice(choice(sources)), choice(choice(sources))
        ) for i in range(pop_size)]

def glean_pop(population, cutoff, fit_test, ft_args=()):
    scores = (fit_test(bug, *ft_args) for bug in population)
    ranked = sorted(zip(population, scores), key=itemgetter(1), reverse=True)
    maxItem = ranked[0]
    new_pop = next(zip(*ranked))[:cutoff]
    return maxItem, new_pop

def repopulate(population, pop_size):
    cutoff = len(population)
    for i in range(pop_size // cutoff):
        population.extend([crossover(choice(population), choice(population))
                           for i in range(cutoff)])
    population.extend([population[i][:] for i in range(pop_size - len(population))])

#Simulator
def simulate(pos_matches, neg_matches, pop_size=50, cutoff=10, threshold=1.0):
    population = generate_pop(pos_matches, neg_matches, pop_size)
    while True:
        for bug in population:
            mutate(bug)

        #Scoring step
        max_item, population = glean_pop(
            population,
            cutoff,
            fitness_test,
            (pos_matches, neg_matches)
            )

        #Exit condition:
        max_regex, max_score = max_item
        if max_score >= threshold:
            return max_score, max_regex
        """
        print(max_score, ''.join(max_regex))
        input("next?")"""

        #Repopulation Step:
        population = list(population)
        repopulate(population, pop_size)

1
これはPythonですか?
グリフィン

1
@JoelCornett独自のsimulate関数を作成することは使用法の一部ですか?あなたのsimulate関数は、引数の#2を使用していません。
ケーシークーボール

1
@Darthfett:いいえ、関数を呼び出す方法の例です。私は(仮想の)内容を説明する変数名を使用しました。パラメーター2についての私の間違いは、タイプミスでした。no_match名前が変更されることになっていますno_match_list。編集
ジョエルコーネット

1
を呼び出すのpopulation = generate_pop(pos_matches, neg_matches, pop_size)はなぜですか、generate_pop関数はneg_matchesパラメーターを使用しませんか?また、関数を呼び出す例を含めることはできますか?のように呼べsimulate(["Hello","World","world"], ["woah","bad","dont match"])ますか?
mbomb007

1
ねえ、私がこれを書いてから数年が経ちました。テストせずにコードを読むだけで、はい、simulate()説明したように関数を呼び出すことができます。はい、あなたは正しいです。最初の母集団を生成するために負のデータを使用しません。
ジョエルコーネット

5

そのようなものに一致するJavaScript正規表現。

/^\/\^\\\/\\\^[\\\[\]\/\^\${},\dd]{34}$/

次のようにテストできます。

(function test() {
    var re =/^\/\^\\\/\\\^[\\\[\]\/\^\${},\dd]{34}$/;
    var m  =/=([^;]+)/.exec(test)[1];
    return re.exec(m);
})();

1
「そのようなもの」とは何ですか?これは何らかの形で実用的または有用ですか?
ケーシーKuball

2
@Darthfett:自分自身とこの正規表現との一致を試みる類似の正規表現と一致します。いいえ、それはいかなる方法でも実用的でも有用でもありませんが、それ自体に一致する唯一の実用的または有用であるが興味深い興味深い正規表現は、正規表現に一致する正規表現です。これが行われました。
Ry-
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.