所以,基本上,我目前正在开发一个从 html 代码中提取答案并将其存储到数组中的程序。问题是,当我尝试创建一个模式来分隔答案时,我似乎无法做出“或”声明。
答案在 html 代码中存储如下:
['h','e','l','l','o',' ','w','o','r','l','d']
我的问题是,当我将其写入字符串时,模式无法识别带有空格(' '
)的字符串,因此当我将其写入文件时,显示的是 helloworld
,没有空格。我想做的是一个同时检测字母和空格的模式,但我不知道如何在模式中间制作“或”语句。
这是我现在的模式,它只检测字母:
Pattern p= Pattern.compile("'[A-Z]+'");
编辑:仍然不起作用...你认为这可能是别的什么吗? 这是我的代码的一部分(抱歉,我知道这是一团糟):
// creates a String containing the letters separated by ' '
public static String createString(BufferedReader in,BufferedWriter out, String texto) throws IOException{
StringBuilder sb= new StringBuilder();
Pattern p = Pattern.compile("'[A-Z '']'");
Matcher m= p.matcher(texto);
while(m.find()){
sb.append(m.group());
}
return sb.toString();
}
//splits the String in order to create an array with nothing but letters
public static void toArray(String s, String[] lista, BufferedWriter out) throws IOException{
lista=s.split("[']");
for(String a:lista){
out.write(a);
System.out.print(a); // to check output
}
}
最佳答案
只需在字符类中添加一个空格即可:
public class HelloWorldRegex {
public static void main(final String... args) {
final String regex = "'([A-Z ])'";
final Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
final String input = "['h','e','l','l','o',' ','w','o','r','l','d']";
final Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.print(matcher.group(1));
}
}
}
输出: Hello World
在线测试正则表达式:https://regex101.com/r/eL8uT9/3
关于java - 如何在java模式中创建 "or"语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30227533/