[英]Get the index of matched string with regex
我试图获取标签之间的内容。 所以我也为此制作了正则表达式。
final String REGEX_BOLD_END = ".*[<][/][B|b][>].*";
String input = "<B>Contetnt here</B>";
Pattern pattern_start = Pattern.compile(".*[<][B|b][>].*");
Matcher matcher_start = pattern_start.matcher(input);
Pattern pattern_end = Pattern.compile(REGEX_BOLD_END);
Matcher matcher_end = pattern_end.matcher(input);
System.out.println("Tag open");
if (matcher_start.matches()) {
System.out.println("At:" + matcher_start.start() + "\tTo:" + matcher_start.end());
System.out.println(matcher_start.group(0));
} else {
System.out.println("Not matched");
}
System.out.println("Tag Close");
if (matcher_end.matches()) {
System.out.print("At:" + matcher_end.start() + "\tTo:" + matcher_end.end());
} else {
System.out.println("Not matched");
}
我的目标是在Content here
获取Content here
。 所以我想要获取开始和结束索引,然后从原始输入中获取子字符串。 但我得到了一些我没想到的东西。
输出:
Tag open
At:0 To:20
<B>Contetnt here</B>
Tag Close
At:0 To:20
请指出我犯错误的地方。
如果您正在考虑使用与正则表达式相关的子字符串,那么您做错了。 正则表达式的重点是不要打扰索引或子串。
试试这个:
Pattern p = Pattern.compile("<[b|B]>(.*)</[b|B]>");
Matcher m = p.matcher(textToMatch);
if (m.find()) {
String firstMatch = m.group(1);
}
编辑 :完成,编译命令行程序,输出“Yay!” 根据要求输入“<b> yay!</ b>”时。
import java.util.regex.*;
class Test {
public static void main(String[] args) {
Pattern p = Pattern.compile("<[b|B]>(.*)</[b|B]>");
Matcher m = p.matcher(args[0]);
if (m.find()) {
System.out.println(m.group(1));
}
else System.out.println("No match");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.