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

2024-04-20 10:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有档案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代码,它找到banner 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))
    }

有人能告诉我怎么写剩下的几行吗??你知道吗

输出应该只需要修剪以banner motd\u开始并以\u结束的行,以及banner motd\u和\u之间的行。你知道吗

你知道吗abc.text公司你知道吗

feature bgp

interface e1/1

vrf myvrf_50000

interface e1/5

Tags: textconfigstringifmodeline公司interface
1条回答
网友
1楼 · 发布于 2024-04-20 10:20:37

基本上,使用regex可以简化逻辑。所以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");
        }

    }

相关问题 更多 >