[英]Java how to use pattern matcher using regular expressions to find certain string
I am not familiar with Patterns & matchers, and I am pretty stuck with this problem. 我对模式和匹配器不熟悉,因此我对这个问题深感困惑。
I have a string that I would like to manipulate in Java. 我有一个要在Java中操作的字符串。 I understand that I have to use
我了解我必须使用
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(in);
while(m.find()) {
String found = m.group(1).toString();
}
But in my string, let's say I have the following examples: 但在我的字符串中,假设我有以下示例:
String in = "test anything goes here [A#1234|567]"; //OR
String in = "test anything goes here [B#1234|567]"; //OR
String in = "test anything goes here [C#1234|567]";
I want to find [A# | ]
我想找到
[A# | ]
[A# | ]
or [B# | ]
[A# | ]
或[B# | ]
[B# | ]
or [C# | ]
[B# | ]
或[C# | ]
[C# | ]
in the string, how do I use the regex to find the expression? [C# | ]
在字符串中,如何使用正则表达式查找表达式?
Use [ABC]#
in your regex to match your expression. 在正则表达式中使用
[ABC]#
来匹配您的表达式。
Pattern p = Pattern.compile("(\\[[ABC]#.*?\\])");
If the fields are digit then you can safely use \\d+
如果字段是数字,则可以安全地使用
\\d+
Pattern p = Pattern.compile("(\\[[ABC]#\\d+\\|\\d+\\])");
I'd use a simple Pattern
as in the following example: 我将在以下示例中使用一个简单的
Pattern
:
String[] in = { "test anything goes here [A#1234|567]",
"test anything goes here [B#1234|567]",
"test anything goes here [C#1234|567]" };
Pattern p = Pattern.compile("\\[[A-Z]#\\d+\\|\\d+\\]");
for (String s: in) {
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println("Found: " + m.group());
}
}
}
Output 产量
Found: [A#1234|567]
Found: [B#1234|567]
Found: [C#1234|567]
I'm assuming here that your Pattern
has specific restrictions: 我在这里假设您的
Pattern
有特定的限制:
[
[
#
#
|
|
]
]
Try: 尝试:
Pattern p = Pattern.compile("(\\\\[[AZ]#.*\\\\])");
If you want to match any capital A through Z. Unclear if you want all the data between []
though. 如果要匹配任何大写字母A到Z。但是不清楚是否需要
[]
之间的所有数据。
My solution: 我的解决方案:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Some {
public static void main(String[] args) throws java.lang.Exception {
String[] in = {
"test anything goes here [A#1234|567]",
"test anything goes here [B#1234|567]",
"test anything goes here [C#1234|567]"
};
Pattern p = Pattern.compile("\\[(.*?)\\]");
for (String s: in ) {
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println("Found: " + m.group().replaceAll("\\d", ""));
}
}
}
}
This uses your original regex. 这使用您的原始正则表达式。
Demo: http://ideone.com/4Z5oYD 演示: http : //ideone.com/4Z5oYD
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.