If 应该过滤掉换行符而不是过滤换行符的语句。
If statement that is supposed to filter out newline not filtering new lines.
我正在编写一个正则表达式模式,该模式通过 HTML 标签进行过滤并仅打印有效标签的内容以供练习。虽然模式本身似乎正确匹配标签,但我 运行 在打印它们时遇到了问题。
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class HTMLPattern{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int testCases = Integer.parseInt(in.nextLine());
while(testCases>0){
String line = in.nextLine();
String tagPattern = "<([^>]+)>([^<]*?)</\1>";
Pattern p = Pattern.compile(tagPattern, Pattern.MULTILINE);
Matcher m = p.matcher(line);
if(m.find()){
//checks if the output equals a newline
if(m.group(2).matches("[\n\r]+")){
System.out.println("None");
}else{
System.out.println(m.group(2));
}
}else{
System.out.println("None");
}
testCases--;
}
}
}
输入时:
3
<a>test</a>
<b></b>
<c>test</c>
我的输出应该是:
test
None
test
但是而不是它是:
test
test
我的问题是:为什么我的 if 语句没有捕获换行符并打印 "None"?
没有新行,只有空字符串,尝试像这样匹配空字符串:
if (m.group(2).matches("^$")) {
或检查 length
字符串:
if (m.group(2).length() == 0) {
原来 if 语句中没有换行符。虽然我之前尝试检查 if(m.group(2) == null)
失败了,但 .isEmpty() 方法正确匹配了我正在测试的空值:
if(m.find()){
if(m.group(2).isEmpty()){
System.out.println("None");
}else{
System.out.println(m.group(2));
}
}else{
System.out.println("None");
}
我正在编写一个正则表达式模式,该模式通过 HTML 标签进行过滤并仅打印有效标签的内容以供练习。虽然模式本身似乎正确匹配标签,但我 运行 在打印它们时遇到了问题。
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class HTMLPattern{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int testCases = Integer.parseInt(in.nextLine());
while(testCases>0){
String line = in.nextLine();
String tagPattern = "<([^>]+)>([^<]*?)</\1>";
Pattern p = Pattern.compile(tagPattern, Pattern.MULTILINE);
Matcher m = p.matcher(line);
if(m.find()){
//checks if the output equals a newline
if(m.group(2).matches("[\n\r]+")){
System.out.println("None");
}else{
System.out.println(m.group(2));
}
}else{
System.out.println("None");
}
testCases--;
}
}
}
输入时:
3
<a>test</a>
<b></b>
<c>test</c>
我的输出应该是:
test
None
test
但是而不是它是:
test
test
我的问题是:为什么我的 if 语句没有捕获换行符并打印 "None"?
没有新行,只有空字符串,尝试像这样匹配空字符串:
if (m.group(2).matches("^$")) {
或检查 length
字符串:
if (m.group(2).length() == 0) {
原来 if 语句中没有换行符。虽然我之前尝试检查 if(m.group(2) == null)
失败了,但 .isEmpty() 方法正确匹配了我正在测试的空值:
if(m.find()){
if(m.group(2).isEmpty()){
System.out.println("None");
}else{
System.out.println(m.group(2));
}
}else{
System.out.println("None");
}