Java regular expression example
Example 1: match ${*}
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExpr {
public static void main(String args[]) {
Pattern pat = Pattern.compile("\\Q${\\E[^}]*}");// ${.*}
String input = "123 ${abc} 456 ${xyz} abc ";
Matcher matcher = pat.matcher(input);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
System.out.println("start=" + start + ", end=" + end
+ ", match string=" + input.substring(start, end));
}
}
}
Output:
start=4, end=10, match string=${abc}
start=15, end=21, match string=${xyz}
Example 2: match [*]
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExpr2 {
public static void main(String args[]) {
Pattern pat = Pattern.compile("\\Q[\\E[^]]*]");// [xxx]
String input = "123 [abc] 456 [xyz] abc ";
Matcher matcher = pat.matcher(input);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
System.out.println("start=" + start + ", end=" + end
+ ", match=" + input.substring(start+1, end-1));
}
}
}
Output:
start=4, end=9, match string=abc
start=14, end=19, match string=xyz
0 Comments:
Post a Comment
<< Home