我需要一些帮助来从字符串中提取多个子字符串.字符串的示例如下所示: String str = "What is Mytag a exp 5 exp 3 written as a single power of ia/i Mytag yx4 and the double power of bx+y/b Mytag 3xy4"; 我想在“
String str = "What is <Mytag a exp 5 exp 3> written as a single power of <i>a</i> <Mytag yx4> and the double power of <b>x+y</b> <Mytag 3xy4>";
我想在“< Mytag”和“>”之间获得子串
所以我的愿望输出将是
1)exp 5 exp 3
2)yx4
3)3xy4
我已经尝试使用Scanner并对我获得第一个字符串成功的所有内容进行子串,但是第二次和第三次出现的问题.
在子字符串方法中,我成功获得所有tages“< Mytag”的索引,但无法获得正确的索引“>”因为它也带有粗体和斜体.
正如Rohit Jain所说,正则表达式.这是功能代码:// import java.io.Console; import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexTestHarness { public static void main(String[] args){ // Console console = System.console(); // Not needed Pattern pattern = Pattern.compile("<Mytag([^>]*)>"); String myString = "What is <Mytag a exp 5 exp 3> written as a single power of <i>a</i> <Mytag yx4> and the double power of <b>x+y</b> <Mytag 3xy4>"; Matcher matcher = pattern.matcher(myString); while (matcher.find()) { // Rohit Jain observation System.out.println(matcher.group(1)); } } }
资料来源:Java Regex tutorial.