Java 请求正则表达式
以下是我的文本作为条目:Java 请求正则表达式,java,regex,Java,Regex,以下是我的文本作为条目: This is An Image File [LoadImage:'image1.jpg'] this is Another Image [LoadImage:'image2.jpg'] 我需要以java数组的形式获取[LoadImage:'*']开始和结束位置这是您要查找的吗?如果是,则使用regex的分组功能,该功能通过使用括号()进行分组,并使用Matcher#group()方法获得它 示例代码: String[] array = new String[] {
This is An Image File [LoadImage:'image1.jpg']
this is Another Image [LoadImage:'image2.jpg']
我需要以java数组的形式获取
[LoadImage:'*']
开始和结束位置这是您要查找的吗?如果是,则使用regex的分组功能,该功能通过使用括号()
进行分组,并使用Matcher#group()
方法获得它
示例代码:
String[] array = new String[] { "This is An Image File [LoadImage:'image1.jpg']",
"this is Another Image [LoadImage:'image2.jpg']" };
Pattern p = Pattern.compile("(\\[LoadImage:.*?\\])");
for (String s : array) {
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(s + " : found:" + m.group(1) + " : start:" + m.start()
+ " : end:" + m.end());
}
}
输出:
This is An Image File [LoadImage:'image1.jpg'] : found:[LoadImage:'image1.jpg'] : start:22 : end:46
this is Another Image [LoadImage:'image2.jpg'] : found:[LoadImage:'image2.jpg'] : start:22 : end:46
Nishant已经给了你答案,但是如果你害怕
[]
内撇号,请使用:
int[] arr = new int[]{str.indexOf('['), str.lastIndexOf(']')}
组1中的正则表达式:*\[(.*)\]
就是您要查找的。请看这里:
输出
“image1.jpg”
“image2.jpg”如果需要位置,这里甚至不需要正则表达式。。一个简单的字符串#indexOf()就可以了。你说的位置是什么意思?此外,还可以添加所需数组的示例。
int[]arr=new int[]{str.indexOf('['),str.indexOf(']')}
应该这样做。实际上indexOf
返回每个[]
的索引,但是我需要处理它,如果它像[LoadImage:'*']
`正则表达式不工作,请测试一下,输出像这样found::22-95=>[LoadImage:'image1.jpg',这是另一个图像[LoadImage:'image2.jpg']
你能告诉我吗,您想要实现什么?根据您的问题,您正在寻找[LoadImage:'*']
?如果没有,那么在接受之前先问一个问题?我从不喜欢不接受答案。慢慢来,先测试一下,然后接受任何答案。你知道,在正则表达式中只有一个变化,你想用括号对它进行分组,这个括号是别人复制的。请再次阅读我文章的第一行,这可能有助于您了解正则表达式分组的工作原理?
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String s = "This is An Image File [LoadImage:'image1.jpg'] this is Another Image [LoadImage:'image2.jpg']";
Pattern p = Pattern.compile("\\[LoadImage:(.*?)\\]");
Matcher m = p.matcher(s);
while(m.find()) {
System.out.println(m.group(1));
}
}
}