0

I have a FIle with following kind of input

<title>Page title1</title>
<title>Page title2</title>
<title>Page title3</title>
<title>Page title4</title>
<title>Page title5</title>
<title>Page title6</title>
<title>Page title7</title>
<title>Page title8</title>
<title>Page title9</title>

I want to extract contents between title I use this code

Pattern pattern = Pattern.compile("(?i)(<title.*?>)(.+?)(</title>)");
Matcher matcher = pattern.matcher(test);
 while (matcher.find()) {
System.out.println(matcher.group().toString());
 }

but I get no output. What am I doing wrong?

4 Answers 4

2

without grouping:

(?<=<title>)[^<]*

but if it is a valid xml doc, better avoid to parse it with regex.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi. Its not. I tried this regex too, its is still not working.. Pattern pattern = Pattern.compile("(?<=<title>)[^<]*");
0

Using your example, simply specify which group you want when printing, which for your purposes would be group 2:

System.out.println(matcher.group(2).toString());

Additionally, considering you get "no output", you should ensure your input string "test" actually contains what you think it does. I recommend this based on the fact that your code does work and it should print the entire match as is.

Comments

0

try this pattern (?<=<title>).*(?=<\\/title>)

Comments

0
 Pattern pattern = Pattern.compile("(?i)(<title.*?>)(.+?)(</title>)");
 Matcher matcher = pattern.matcher(test);
 while (matcher.find()) 
 {
   System.out.println(matcher.group().toString());
 }

Above is very costly operation. you can simply use indexof on string

String str="<title>Page title1</title>";
int index=str.indexOf("<title>");
int lastIndex=str.indexOf("</title>");
String literal=str.substring(index+5,lastIndex);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.