【问题标题】:Converting conversations IRC logs with regex?使用正则表达式转换对话 IRC 日志?
【发布时间】:2013-04-02 23:09:18
【问题描述】:

所以这里我有来自 BNC 格式的 IRC 日志(其中 [AA:BB:CC] 不是实际时间,只是加载时间):

[AA:BB:CC] <Person1> [re:al:ts] BLAH BLAH BLAH
[AA:BB:CC] <Person2> [an:ot:he] BLAH BLAH BLAH
[AA:BB:CC] <Person3> [rr:ea:lt] BLAH BLAH BLAH
[AA:BB:CC] <Person4> [im:es:tp] BLAH BLAH BLAH

我想把它转换成:

[re:al:ts] <Person1> BLAH BLAH BLAH
[an:ot:he] <Person2> BLAH BLAH BLAH
[rr:ea:lt] <Person3> BLAH BLAH BLAH
[im:es:tp] <Person4> BLAH BLAH BLAH

这在技术上可行吗?我看到 [AA:BB:CC] 可以很容易地被删除,但是我如何保留真正的时间戳并将它们移动到行的 /beginning/ 而不删除“blah blah blah”或“”s?老实说,我不是很精通正则表达式...

谢谢 :) 枫树

【问题讨论】:

  • 我认为时间戳是hh:mm:ss 的形式是否正确?你能提供一个真实的例子吗?除非你想让我猜你文件的内容是什么。

标签: regex irc reformat reformatting


【解决方案1】:

如果你不使用多行匹配,试试这个正则表达式:

/\[.*?]( <.*?> )\[(.*?)]/g

您将替换为:

"[$2]$1"

【讨论】:

    【解决方案2】:

    一个例子来解决:

    perl -pe 's/^\[..:..:..](.*)(\[..:..:..]) (.*)/$2$1$3/' <<EOT
    [AA:BB:CC] <Person1> [re:al:ts] BLAH BLAH BLAH
    [AA:BB:CC] <Person2> [an:ot:he] BLAH BLAH BLAH
    [AA:BB:CC] <Person3> [rr:ea:lt] BLAH BLAH BLAH
    [AA:BB:CC] <Person4> [im:es:tp] BLAH BLAH BLAH
    EOT
    

    输出:

    [re:al:ts] <Person1> BLAH BLAH BLAH
    [an:ot:he] <Person2> BLAH BLAH BLAH
    [rr:ea:lt] <Person3> BLAH BLAH BLAH
    [im:es:tp] <Person4> BLAH BLAH BLAH
    

    如果 AA、BB、CC、... 是数字,则在 perl 正则表达式中使用 \d\d 而不是 ..

    【讨论】:

    • 有趣,我没有意识到你不必逃避结束的“]”。 perl 中的代码更简洁一些...
    • @bmorris591 是的,-p 和 -n args 大大减少了开销。
    【解决方案3】:

    让我们先做一些假设。

    1. [hh:mm:ss] 形式的时间戳,10 以下的秒/分钟表示为 01 等。
    2. 人员字符串不包含“[”

    然后以下正则表达式将起作用:

    ^\[\d{2}:\d{2}:\d{2}\]([^\[]++)(\[\d{2}:\d{2}:\d{2}\])(.*)$
    

    这是一个用 Java 编写的测试用例:

    public static void main(String[] args) {
        final String[] strings = {"[AA:BB:CC] <Person1> [re:al:ts] BLAH BLAH BLAH",
            "[12:12:11] <Person2> [14:10:25] BLAH BLAH BLAH",
            "[12:12:11] <Person3> [14:10:25] BLAH BLAH BLAH",
            "[12:12:11] <Person4> [14:10:25] BLAH BLAH BLAH"};
        final Pattern pattern = Pattern.compile("^\\[\\d{2}:\\d{2}:\\d{2}\\]([^\\[]++)(\\[\\d{2}:\\d{2}:\\d{2}\\])(.*)$");
        for(final String string : strings) {
            final Matcher matcher = pattern.matcher(string);
            if(matcher.matches()) {
                System.out.println(matcher.group(2) + matcher.group(1) + matcher.group(3));
            }
        }
    }
    

    输出:

    [14:10:25] <Person2>  BLAH BLAH BLAH
    [14:10:25] <Person3>  BLAH BLAH BLAH
    [14:10:25] <Person4>  BLAH BLAH BLAH
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      相关资源
      最近更新 更多