如何将python代码转换为java代码?

时间:2019-05-17 06:46:10

标签: python java-8

我有文件abc.text

abc.text

feature bgp

interface e1/1

banner motd _ Interface Eth0

interface e1/2

interface e1/3

interface e1/4

_

vrf myvrf_50000

interface e1/5

我有一个python代码,该代码可找到条幅motd之后的第一个字符,并以该字符结尾并删除该行。

    for line in config:
        banner_line = re.match(r'banner motd (.)', line)
        if banner_line:
            banner_end_char = banner_line.group(1)
            LOGGER.debug("Banner end char %s %s", banner_end_char, line)
            device_config_tree['.banner'].append(line)
            # print banner_end_char
            if line[13:].count(banner_end_char) == 0:
                banner_mode = True
        elif banner_mode:
            depth = 1
            device_config_tree['.banner'].append(line)
            LOGGER.debug("Banner mode %s ", line)
            if banner_end_char in line:
                banner_mode = False
            continue

我已经用Java编写过代码

String line = new String(Files.readAllBytes(Paths.get("E:\\JavainHolidays\\LearnJava\\Practice\\abc.txt")), StandardCharsets.UTF_8);

    System.out.println(line);

    String pattern = "abs mod (.)";

    Pattern r = Pattern.compile(pattern);

    Matcher m = r.matcher(line);
    if (m.find())
    {
    System.out.println("\nFound Value: " + m.group(1))
    }

有人可以告诉我如何写其余几行吗?

应该只需要修剪输出以横幅motd _结束并以_结束的线条以及横幅motd _和_之间的线条即可。

abc.text

feature bgp

interface e1/1

vrf myvrf_50000

interface e1/5

1 个答案:

答案 0 :(得分:0)

基本上,可以使用正则表达式简化逻辑。因此,可以像下面这样转换python代码。

import re

input_file = 'input_file.txt'

file_content = open(input_file).read()
bc = re.findall('banner motd (.)', file_content)[0]

file_content = re.sub('banner motd ' + bc + '.*?' + bc, '', file_content, flags=re.DOTALL)

# This is the output file content. Can be written to output file
print(file_content)

在JAVA中使用相同的逻辑。该代码可以编写如下。

private static void removeBanners() throws IOException {
        String inputFile = "input_file.txt";

        String fileContent = new String(Files.readAllBytes(Paths.get(inputFile)));

        final Matcher matcher = Pattern.compile("banner motd (.)").matcher(fileContent);

        String bannerChar = null;
        if (matcher.find()) {
            bannerChar = matcher.group(1);
        }

        if (bannerChar != null) {
            final Matcher matcher1 = Pattern.compile("banner motd " + bannerChar + ".*?" + bannerChar, Pattern.DOTALL).matcher(fileContent);
            String result = fileContent;
            while (matcher1.find()) {
                result = result.replaceAll(matcher1.group(), "");
            }
            System.out.println(result);
        } else {
            System.out.println("No banner char found");
        }

    }