I have a String which contains the following sub string:
[Qual:3] [Text:PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1] [Elem:123]
I'd like to extract the part between
How do I do this?Answer1:
Pattern p = Pattern.compile("\\[Text:(.*?)\\]");
Matcher m = p.matcher("[Qual:3] [Text:PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1] [Elem:123]");
\\] are to escape the brackets, which are special characters in regexes. The
.*? is a non-greedy quantifier, so it stops gobbling up characters when it reaches the closing bracket. This part of the regex is given inside a capturing group
(), which you can access with
Use the following string as the regex:
The first capture group will give you exactly the substring you want.
The non-greedy match (
.*?) is required to make it stop at the first
] rather than also including
String.substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
You could use this to remove the start and end of the string,
You could use
To get the index of the start and end of the match and copy the contents to a new result string.
You could use
However writing regular expressions can get difficult,
<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html" rel="nofollow">http://docs.oracle.com/javase/6/docs/api/java/lang/String.html</a>
I hope this helps.Answer4:
Instead of using
"\\[Text:(.*?)\\]", as others have suggested, I'd go one step further and use lookarounds to filter out the text you don't want:
This will match exactly the text you want without having to select a capturing group.