Reputation: 778
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. 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# | ]
or [B# | ]
or [C# | ]
in the string, how do I use the regex to find the expression?
Upvotes: 1
Views: 191
Reputation: 59252
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
Upvotes: 0
Reputation: 48404
I'd use a simple Pattern
as in the following example:
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:
[
#
|
]
Upvotes: 1
Reputation: 1491
Try:
Pattern p = Pattern.compile("(\\[[A-Z]#.*\\])");
If you want to match any capital A through Z. Unclear if you want all the data between []
though.
Upvotes: 0
Reputation: 39365
Use [ABC]#
in your regex to match your expression.
Pattern p = Pattern.compile("(\\[[ABC]#.*?\\])");
If the fields are digit then you can safely use \d+
Pattern p = Pattern.compile("(\\[[ABC]#\\d+\\|\\d+\\])");
Upvotes: 1