Java regex how to find parental match?

Any page from Wikipedia :

... abas asdn asf asfs af {{Template1 |a = Name surname |b = jhsdf sdf |c = {{Template2}} |d = |e = [[f]] and [[g]] |h = asd asdasfgasgasg asgas jygh trdx dftf xcth |i = 73 |j = {{Template2|abc|123}} |j = {{Template3|aa=kkk|bb={{Template4|cc=uu}}}} }} asd wetd gdsgwew g {{OtherTemplate |sdf = 213 }} ... 

How can I find Template1 content (start |a end is }} ) with Java regular expressions?

I tried:

 String pattern = "\\{\\{\\s*Template1\\s*(.*?)\\}\\}"; Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); Matcher m = p.matcher(content); while (m.find()) { if (!m.group().equals("")) { System.out.println(m.group()); System.out.println("-----------------------"); } } 

But here the regex finds the first }} (which is Template2 }} ) and then stops.
I want to pass }} any {{ open. Then I want to find a match with my parents.

I want to get the top Template1 content between the vertices {{ and }} ?.

EDIT:

Note that after removing the spaces, I parse the content .

 content.replaceAll("\\s+",""); 

Think of the content as writing one line.

+7
java string regex match wikipedia
source share
3 answers

/^{{Template1(.*?)^}}/sm

returns:

 |a = Name surname |b = jhsdf sdf |c = {{Template2}} |d = |e = [[f]] and [[g]] |h = asd asdasfgasgasg asgas jygh trdx dftf xcth |i = 73 |j = {{Template2|abc|123}} |j = {{Template3|aa=kkk|bb={{Template4|cc=uu}}}} 

https://regex101.com/r/qC6cM1/1 (DEMO)

+1
source share
 \\{\\{\\s*Template1\\s*(.*?)\\n\\}\\} ^^ 

Just turn on \n . Watch the demo.

https://regex101.com/r/uF4oY4/72

0
source share

I think in this case the parser would be better than jub, but if you want a regular expression, how about this:

 {{Template1(?:[^{}]*?(?:{{[^}]+?}}))+(?:[}\n\s]+})* 

Demo

I assumed that your input looks like a single line.

0
source share

All Articles