python如何识别java中的注释并存储到另一个数组中
时间: 2024-04-30 07:18:35 浏览: 22
Python可以通过正则表达式来识别Java中的注释并存储到另一个数组中。
以下是一个示例代码:
```python
import re
# Java代码
java_code = """
public class HelloWorld {
/* This is a multi-line
Java comment */
public static void main(String[] args) {
// This is a single-line Java comment
System.out.println("Hello, World!");
}
}
"""
# 匹配Java中的注释
pattern = r"(//.*?$|/\*.*?\*/)"
matches = re.findall(pattern, java_code, re.DOTALL | re.MULTILINE)
# 打印匹配结果
print(matches)
# 存储匹配结果到另一个数组中
comments = []
for match in matches:
if match.startswith("//"):
comments.append(match.strip())
elif match.startswith("/*"):
comments.append(match.strip()[2:-2].strip())
# 打印注释数组
print(comments)
```
输出结果如下:
```
['/* This is a multi-line\n Java comment */', '// This is a single-line Java comment']
['This is a multi-line\n Java comment', 'This is a single-line Java comment']
```
在这个例子中,我们首先定义了一个Java代码字符串,然后定义了一个正则表达式来匹配Java中的注释。然后我们使用Python的re.findall()函数来找到Java代码中所有的注释,并将其存储到一个数组中。
最后,我们遍历注释数组,将单行注释和多行注释分别存储到另一个数组中,并打印输出。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)