【问题标题】:How to use back reference in Java regex如何在 Java 正则表达式中使用反向引用
【发布时间】:2014-10-15 21:55:32
【问题描述】:

RE 专家的问题:考虑以下 Perl 脚本:

my @lines = (
        "Once upon a time in a galaxy far, far away, there lived\n",
        "this _idiot_ trying to _mark up_ a few lines of\n",
        "marked down text using yet another _language_.\n");

foreach (@lines) {
        s|_(.+?)_|<em>$1</em>|g;
        print
}

% perl [aboveScript] 的输出是

Once upon a time in a galaxy far, far away, there lived
this <em>idiot</em> trying to <em>mark up</em> a few lines of
marked down text using yet another <em>language</em>.

我正在尝试在 Java 中实现这一点。我想出的课程如下。它有效,我得到与上面相同的输出,但我很确定这不是这样做的方法。我的问题 - 你将如何实现“parseLine()”方法?

import java.util.*;
import java.util.regex.*;

public class Reglob {

        private final static Pattern emPattern = Pattern.compile ("_(.+?)_");

        public void parseLine (String[] lines) {
                for (String line : lines) {
                        List<Integer>   bList = new ArrayList<Integer>(),
                                        eList = new ArrayList<Integer>();
                        Matcher m = emPattern.matcher (line);
                        int n = 0;
                        while (m.find()) {
                                // System.out.println ("Match indices: " + m.start() + ", " + m.end());
                                bList.add (m.start());
                                eList.add (m.end());
                                n++;
                        }
                        if (n == 0) {
                                System.out.println (line);
                        } else {
                                String s = line.substring (0, bList.get(0));
                                for (int i = 0 ; i < n-1 ; i++) {
                                    s += "<em>"
                                        + line.substring(1+bList.get(i),eList.get(i)-1)
                                        + "</em>" + line.substring (eList.get(i), bList.get(i+1));
                                }
                                s += "<em>"
                                        + line.substring(1+bList.get(n-1),eList.get(n-1)-1)
                                        + "</em>" + line.substring (eList.get(n-1), line.length());
                                System.out.println (s);
        }}}

        public static void main (String[] args) {
                String[] lines = {
                        "Once upon a time in a galaxy far, far away, there lived",
                        "this _idiot_ trying to _mark up_ a few lines of",
                        "marked down text using yet another _language_."};
                new Reglob().parseLine (lines);
}}

【问题讨论】:

  • 这个问题只有专家才能回答?我觉得受到了歧视……
  • @200_success 的欺骗被豆腐啤酒回答了。我怎么错过了豆腐啤酒? Can Berk Güder 的另一个答案,听起来像是另一种异国情调的啤酒,也许是瑞典的,而且很好。
  • Java 正则表达式中除了我自己之外的任何人都是专家 - 我只是一个新手。现在我明白了……这么多正确答案,不知道该选哪一个!我什至不需要这个模式 - 哦,好吧!

标签: java regex


【解决方案1】:

这是您的 Perl 脚本的 Java 等价物:

public class Main {
    public static void main(String[] args) {
        String[] lines = {
                "Once upon a time in a galaxy far, far away, there lived\n",
                "this _idiot_ trying to _mark up_ a few lines of\n",
                "marked down text using yet another _language_.\n" };

        for(String line : lines) {
            String output = line.replaceAll("_(.+?)_", "<em>$1</em>");

            System.out.print(output);
        }
    }
}

它输出:

Once upon a time in a galaxy far, far away, there lived
this <em>idiot</em> trying to <em>mark up</em> a few lines of
marked down text using yet another <em>language</em>.

【讨论】:

    【解决方案2】:

    你可以这样做,

    String [] s = {  "Once upon a time in a galaxy far, far away, there lived",
                    "this _idiot_ trying to _mark up_ a few lines of",
                     "marked down text using yet another _language_."};
    for(String s2 : s)
    {
    System.out.println(s2.replaceAll("_([^_]+)_", "<em>$1</em>"));
    }
    

    【讨论】:

      【解决方案3】:

      试试这样的:

      public static final String str = "Once upon a time in a galaxy far, far away, there lived\n" +
              "this _idiot_ trying to _mark up_ a few lines of\n" +
              "marked down text using yet another _language_.\n";
      
      public static void main(String[] args) {
          System.out.println(str.replaceAll("_(.+?)_", "<em>$1</em>"));
      }
      

      这个的输出:

      Once upon a time in a galaxy far, far away, there lived
      this <em>idiot</em> trying to <em>mark up</em> a few lines of
      marked down text using yet another <em>language</em>.
      

      【讨论】:

        【解决方案4】:

        同样,在 Scala 中:

        scala> val text = """Once upon a time in a galaxy far, far away, there lived
             | this _idiot_ trying to _mark up_ a few lines of
             | marked down text using yet another _language_."""
        text: String =
        Once upon a time in a galaxy far, far away, there lived
        this _idiot_ trying to _mark up_ a few lines of
        marked down text using yet another _language_.
        
        scala> val r = "_(.+?)_".r
        r: scala.util.matching.Regex = _(.+?)_
        
        scala> r.replaceAllIn(text, """<em>$1<\em>""")
        res3: String =
        Once upon a time in a galaxy far, far away, there lived
        this <em>idiot<em> trying to <em>mark up<em> a few lines of
        marked down text using yet another <em>language<em>.
        

        我首先在 Scala REPL 中尝试一切,然后转换为 Java。

        但既然你有很多 Java 答案,我会回到 Hulu。

        【讨论】:

          猜你喜欢
          • 2018-07-13
          • 1970-01-01
          • 2022-06-15
          • 1970-01-01
          • 2011-04-04
          • 2012-11-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多