Java 正则表达式获得所有一致性
我需要获取包含此文本的所有字符串 %变量%s此处的某些文本%/variables% 范例Java 正则表达式获得所有一致性,java,regex,match,Java,Regex,Match,我需要获取包含此文本的所有字符串 %变量%s此处的某些文本%/variables% 范例 %enca% something here %variables% take this text %/variables% other stuffs here, I dont need this %variables% I need this too %/variables% other stuffs, etc 我所拥有的是: 我试着这样做: %变量%(.*?)%/变量% 并且是这样工作的(只有一个匹
%enca% something here %variables% take this text %/variables%
other stuffs here, I dont need this
%variables% I need this too %/variables%
other stuffs, etc
我所拥有的是:
我试着这样做:%变量%(.*?)%/变量% 并且是这样工作的(只有一个匹配) 但在Java中不起作用:
private boolean variablesTag(String s)
{
Pattern pattern = Pattern.compile("/%variables%(.*?)%/variables%/gs");
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
//do some stuff...stored, work with the string, etc...
};
return true;
}
如果你能告诉我怎么把绳子拿进去,我真的很感激。
我想要的是:
以这篇文章为例
这也是
我正在使用NetBeans
解决方案
Pattern pattern = Pattern.compile("%variables%(.*?)%/variables%",Pattern.MULTILINE|Pattern.DOTALL);
没有标志不起作用请尝试使用此模式:-
Pattern.compile("%variables%(.*?)%/variables%");
然后像这样得到所需的值。选择你想要的
while(matcher.find()){
System.out.println(matcher.group()); //Prints this "%variables% take this text %/variables%"
System.out.println(matcher.group(1)); //Prints this " take this text"
}
在Java中,正则表达式上不需要“/”分隔符,事实上使用它们是不正确的。如果要向正则表达式添加标志,则有两个参数版本的
Pattern.compile
(请参阅)
改变
Pattern pattern = Pattern.compile("/%variables%(.*?)%/variables%/gs");
例如:
Pattern pattern = Pattern.compile("%variables%(.*?)%/variables%", Pattern.DOTALL);
然后使用循环中的matcher.group(1)
访问捕获的内容
public static void main(String... args) {
String input = "%enca% something here %variables% take this text %/variables% "
+ "other stuffs here, I dont need this"
+ "%variables% I need this too %/variables%"
+ "other stuffs, etc";
Pattern pattern = Pattern.compile("%variables%(.*?)%/variables%");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String s = matcher.group(1);
System.out.format("%s\n", s);
}
}
输出
take this text
I need this too
+1正确。关于斜杠,并不是说“你不需要它们”,而是它们与regex没有任何关系-它们是一个应用程序语言语法构造。没有标志不起作用,我认为是因为文本包含回车符,无论如何,非常感谢你的时间,我感谢没有标志不起作用,我想是因为文本包含回车符,无论如何,非常感谢您的时间,我很感激,Crashman,“字符串输入”中没有CRs。你试着照原样复制我的样品了吗?我想是的,但是。。它应该可以工作..我只是试着在每个[+]”之后添加“\r\n”和“\n”也可以工作。你完全正确,你的代码可以工作,但我真的不知道为什么不能与我的文本一起工作,这里再次是=“%inicio%%encabezado%%variables%%float,var1,10%%/variables%%variables%%int,var1,10%%/variables%%/encabezado%%/inicio%“本文来自jTextArea