Регулярное выражение не возвращает ожидаемые данные

1

У меня есть следующая строка ($ a), и я пытаюсь изолировать текст, начиная с разделителя "|" где слово "президент" до следующего идентичного разделителя "|", у меня есть следующий код, который возвращает больше данных, чем ожидалось.

<?php 
$a = '{{Redirect|Harvard}} {{pp-move-indef}} {{Use mdy dates|date=August  
2014}} {{pp-semi-blp|small=yes}}{{Infobox university |name = Harvard 
University |image_name = Harvard Wreath Logo 1.svg |image_size = |caption 
= [[Seal (emblem)|Seal]] of Harvard University |latin_name = Universitas 
Harvardiana |motto = ''Veritas''Harvard ''Veritas'' appears on the  
university arms; [[Heraldry|heraldically]] speaking, however, a 'motto' 
is a word or phrase displayed on a scroll in conjunction with a shield of 
arms. [https://books.google.com/books?
id=zkQWZaZqZfUC&pg=PA330&lpg=PA330#v=onepage&q&f=false Since 1692] 
University [[seal (device)|seals]] have borne ''Christo et Ecclesiae'' 
(for Christ and the Church) in this manner, arguably making that phrase 
the university motto in a heraldic sense. This legend is otherwise not 
in general use today. |established = 1636An appropriation of £400 toward 
a "school or college" was voted on October 28, 1636 (OS), at a meeting 
which convened on September 8 and was adjourned to October 28. Some 
sources consider October 28, 1636 (OS) (November 7, 1636 NS) to be the 
date of founding. Harvard 1936 tercentenary celebration treated 
September 18 as the founding date, though 1836 bicentennial was 
celebrated on September 8, 1836. Sources: meeting dates, {{cite 
book|first=Josiah|last=Quincy|title=History of Harvard University 
|year=1860 |publisher=Crosby, Nichols, Lee and Co.|location=117 
Washington Street, Boston}}, [https://books.google.com/books?
vid=OCLC11636583&id=KynqxH_4lGUC&pg=RA1-PA586&lpg=RA1-PA586 p. 586], "At 
a Court holden September 8th, 1636 and continued by adjournment to the 
28th of the 8th month (October, 1636)... the Court agreed to give £400 
towards a School or College, whereof £200 to be paid next year...."  
Tercentenary dates: {{cite 
news|url=http://www.time.com/time/
magazine/printout/0,8816,756722,00.html|date=September 28,  
1936|accessdate=September 8, 2006|work=Time|title=Cambridge Birthday}}: 
"Harvard claims birth on the day the Massachusetts Great and General 
Court convened to authorize its founding. This was Sept. 8, 1637 under    
the Julian calendar. Allowing for the ten-day advance of the Gregorian 
calendar, Tercentenary officials arrived at Sept. 18 as the date for the 
third and last big Day of the celebration;" "on Oct. 28, 1636 ... £400 
for that 'school or college' [was voted by] the Great and General Court 
of the [[Massachusetts Bay Colony]]." Bicentennial date: {{cite web 
|url=http://www.news.harvard.edu/gazette/2003/10.02/02-
history.html|publisher=Harvard University|title=Harvard Gazette: This 
Month in Harvard History|date=September 2, 2003 |accessdate=September 15, 
2006|author=Marvin Hightower}}, "Sept. 8, 1836 - Some 1,100 to 1,300 
alumni flock to Harvard Bicentennial, at which a professional choir 
premieres "Fair Harvard." ... guest speaker Josiah Quincy Jr., Class of 
1821, makes a motion, unanimously adopted, 'that this assembly of the 
Alumni be adjourned to meet at this place on September 8, 1936.'" 
Tercentary opening of Quincy sealed package: ''The New York Times,'' 
September 9, 1936, p. 24, "Package Sealed in 1836 Opened at Harvard. It 
Held Letters Written at Bicentenary": "September 8th, 1936: As the first 
formal function in the celebration of Harvard tercentenary, the Harvard 
Alumni Association witnessed the opening by President Conant of the 
'mysterious' package sealed by President Josiah Quincy at the Harvard 
bicentennial in 1836." |mottoeng = Truth |type = [[Private 
university|Private]] â€" [[Research]] |calendar = Semester |endowment = 
$36.4 billion{{As of|2014|06|30}}. {{cite web | title = Harvard Endowment 
Earns 15.4% Return for Fiscal 2014| work = The Wall Street Journal | url  
= http://online.wsj.com/articles/harvard-endowment-earns-15-4-return-for-
fiscal-2014-1411506002 | accessdate=10 October 2014}} |president = [[Drew 
Gilpin Faust]] |students = 21,000{{As of|2014|09|01}}. {{cite web | title  
= Harvard at a Glance| work = Harvard University | url = 
http://www.harvard.edu/harvard-glance | accessdate=27 November 2014}} 
|undergrad = 6,700 |postgrad = 14,500 |staff = |faculty = 4,671{{Cite 
book|last=Office of Institutional Research.|title=Harvard University Fact  
Book|year=2009|chapter=Faculty|url=http://   
www.provost.harvard.edu/institutional_research/Provost_-_09_18-
19facuni.pdf}} ("Unduplicated, Paid Instructional Faculty Count: 2,107. 
Unduplicated instructional faculty count is the most appropriate count 
for general reporting purposes.") |city = [[Cambridge, 
Massachusetts|Cambridge]] |state = [[Massachusetts]] |country = United 
States |campus = [[Urban area|Urban]]{{Convert|210|acre|ha}} (Main  
campus){{Convert|21|acre|ha}} (Medical campus)
{{Convert|360|acre|ha}} (Allston campus)
{{Convert|4500|acre|ha}} (other holdings) |sports = 42 varsity teams   
|athletics = [[National Collegiate Athletic Association|NCAA]] [[Division  
I (NCAA)|Division I]] â€" [[Ivy League]] |nickname = [[Harvard Crimson]] 
|colors = {{color box|#A41034}} [[Crimson]]{{cite web|title=Color - 
Identity Guidelines - Harvard Business  
School|url=http://www.hbs.edu/marketing/color.html|publisher=Harvard 
Business School|accessdate=26 September 2014}} |free_label = Student 
newspaper |free = ''[[The Harvard Crimson]]'' |affiliations = [[National 
Association of Independent Colleges and Universities|NAICU]]
[[Association of Independent Colleges and Universities in  
Massachusetts|AICUM]][[Association of American Universities|AAU]]
[[Universities Research Association|URA]] |website =   
{{URL|http://www.harvard.edu/|Harvard.edu}} |logo = [[File:Harvard 
University logo.PNG|Harvard University logo (with its coat of arms)]]  
|publictransit = [[Harvard (MBTA station)]] }} '''Harvard University''' 
is a [[Private university|private]] [[Ivy League]] [[Doctoral 
university|research university]] in [[Cambridge, 
Massachusetts|Cambridge]], [[Massachusetts]], established in 1636. Its 
history, influence and wealth have made it one of the most prestigious 
universities in the world.{{cite book|title=Making Harvard Modern: The 
Rise of America  
University|last1=Keller|first1=Morton|last2=Keller
|first2=Phyllis|publisher=Oxford University Press|isbn=0-19-514457-
0|quote=Harvard professional schools... won world prestige of a sort 
rarely seen among social institutions. (...) Harvard age, wealth, 
quality, and prestige may well shield it from any conceivable 
vicissitudes.|year=2001|pages=463â€"481}}{{Cite book|title=How Harvard 
Rules: Reason in the Service of Empire|quote=... [Harvard's] tremendous 
institutional power and prestige (...) Within the nation (arguably)  
most prestigious institution of higher learning ...|chapter=Sexual 
Shakedown|pages=326â€"336|year=1989|publisher=South End Press|isbn=0-
89608-284-9|editor1-first=John|last=Spaulding|first=Christina|editor-
last=Trumpbour}}{{cite web|url=http://www.bloomberg.com/news/2011-03-
10/harvard-mit-ranked-most-prestigious-universities-study-
reports.html|title=Harvard, MIT Ranked Most Prestigious Universities, 
Study Reports|author=David Altaner|publisher=Bloomberg|date=March 9, 
2011|accessdate=March 1, 2012}}{{cite book|title=Collier 
Encyclopedia|publisher=Macmillan Educational Co.|year=1986|quote=Harvard 
University, one of the world most prestigious institutions of higher 
learning, was founded in Massachusetts in 1636.}}{{cite 
web|last=Newport|first=Frank|title=Harvard Number One University in Eyes 
of Public Stanford and Yale in second 
place|url=http://www.gallup.com/poll/9109/harvard-number-one-university-
eyes-public.aspx|publisher=Gallup}} Established originally by the 
[[Massachusetts General Court|Massachusetts legislature]] and soon 
thereafter named for [[John Harvard (clergyman)|John Harvard]] (its first 
benefactor), Harvard is the [[Colonial Colleges|United States' oldest 
institution of higher learning]],{{cite book|first1=Frederick 
|last1=Rudolph|title=The American College and 
University|year=1961|page=3|isbn=0-8203-1285-1|publisher=University of 
Georgia Press}} and the [[Harvard Corporation]] (formally, the 
''President and Fellows of Harvard College'')';

$re = "/[^|]*\\bpresident\\b[^|]*/i"; 
if (preg_match_all($re, $a, $result)) {
var_dump($result)
}
?>

Var_dump ($ result) дает мне результаты от "author = Marvin Hightower", однако я ожидал бы результатов, основанных на моем выражении: "| президент = [[Дрю Гилпин Фауст]]". Что мне не хватает?

  • 0
    Я не думаю, что ваш код компилируется ...
  • 0
    Ваше регулярное выражение ищет [^|]* - что означает «что угодно, кроме | трубы». ^ Отрицает класс персонажа.
Теги:
preg-match-all

1 ответ

2
Лучший ответ
(?:^|(?<=\|))[^|]*\bpresident\b[^|]*(?=\||$)

Используйте это. Смотрите демоверсию.

https://regex101.com/r/sS2dM8/3

Проблема состоит в том, что из-за рыхлых концов он попадает в катастрофическое обратное отслеживание. Просто исправьте концы, и он отлично работает. Регулярное само по себе не является неправильным, но оно генерирует слишком много комбинаций на больших данных и не приводит к катастрофической ошибке.

  • 0
    Большое спасибо! Работает шарм!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню