正则表达式:在Java中匹配和排除; php风味;

时间:2017-03-08 16:31:00

标签: java php regex

我需要一些这个正则表达式的帮助:

(?<=.)(\^FD).*(\^FS)

我正在尝试匹配 ^ FD ^ FS ,但只有当它们在线路上都可用时才会匹配;因此排除介于两者之间的所有内容

^FO638,340^FDPermit^FS
          ^^^      ^^^

^FO638,390^FD123456^FS
          ^^^      ^^^

^FO050,500^GB700,1,3^FS
                    xxx

^FD^FS
^^^^^^

我一直在使用https://regex101.com/来构建表达式,它似乎在网络上正确匹配,但在我的程序中却没有 - &gt;它匹配 ^ FD ^ FS

之间的所有内容

2 个答案:

答案 0 :(得分:0)

排除是什么意思? 并且,正则表达式真的有必要吗?

public class Test
{
   public static void main(final String... args) {
      final String line = "^FO638,340^FDPermit^FS";
      final int fdIndex = line.indexOf("^FD") + 3;
      final int fsIndex = line.indexOf("^FS");

      if (fdIndex > -1 && fsIndex > -1) {
         line.substring(fdIndex, fsIndex);
      }
   }
}

如果你想排除里面的内容:

public class Test
{
   public static void main(final String args[]) {
      final String line = "^FO638,340^FDPermit^FSdddd";
      final int fdIndex = line.indexOf("^FD");
      final int fsIndex = line.indexOf("^FS");

      if (fdIndex > -1 && fsIndex > -1) {
         System.out.println(line.substring(0, fdIndex) + line.substring(fsIndex + 3));
      }
   }
}

答案 1 :(得分:0)

我没有看到问题。这是你在java中使用它的方式,它返回与regex101.com相同的

number(../node/@begin)

输出结果为:

public static void main(String[] args) {
        String text = "^FO638,340^FDPermit^FS\n          ^^^      ^^^\n\n^FO638,390^FD123456^FS\n          ^^^      ^^^\n\n^FO050,500^GB700,1,3^FS\n                    xxx\n\n^FD^FS\n^^^^^^";

        Pattern pattern = Pattern.compile("(?<=.)(\\^FD).*(\\^FS)");
        Matcher matcher = pattern.matcher(text);

        while(matcher.find()){
            System.out.print("Start index: " + matcher.start());
            System.out.print(" End index: " + matcher.end() + " ");
            System.out.println(matcher.group());
        }
    }

这是网站的答案

Start index: 10 End index: 22 ^FDPermit^FS
Start index: 57 End index: 69 ^FD123456^FS

您可以使用下一个代码打印组

Match 1
Full match  10-22   `^FDPermit^FS`
Group 1.    10-13   `^FD`
Group 2.    19-22   `^FS`
Match 2
Full match  57-69   `^FD123456^FS`
Group 1.    57-60   `^FD`
Group 2.    66-69   `^FS`