Вход

Просмотр полной версии : Получить все английские слов на странице


pautinaweb
17.05.2019, 00:10
Помогите написать регулярное выражение, мне необходимо получить получить все английские слова на странице, или ткните куда копать.

Можно ли регуляркой все слова из английских букв получить, или здесь циклом проходить по всем словам придется и потом уже проверять на наличие букв?

ksa
17.05.2019, 07:35
Небольшой пример...

var txt='Start Главная > Форум » Javascript » Events/DOM/Window » Получить все английские слов на странице stop';
alert(txt.match(/(^|[\s\/])[a-z]+(?=[\s\/]|$)/gi));

laimas
17.05.2019, 07:42
ksa, можно проще, искать по границе слова /\b[\w]+/

ksa
17.05.2019, 07:44
Проще это хорошо.:D

ksa
17.05.2019, 07:50
Но не всегда...
var txt='Start ГлавнаяTest > Форум » Javascript123 » Events/DOM/Window » Получить все английские слов на странице stop';
alert(txt.match(/\b[\w]+/gi));

Но это уже пускай ТС думает...

Malleys
18.05.2019, 05:25
Некоторые слова пишутся через дефис. (Например, un-ionized (not in ion form), сравните с unionized (organized into trade unions), сейчас некоторые понятия пишут с определением Electronic, например, e-mail, e-learning, e-government, e-commerce и пр.) Такой дефис обязателен.

Также используется апостроф (например, the Eagle’s feathers, fish ‘n’ chips, и пр.)

Аббревиатуры могут писаться через точку. (сравните USA, FBI, RIP c U.S.A., F.B.I., R.I.P.)

Чтобы показать, что гласная буква образует отдельный слог, над ним может ставиться умляут. (например, zoölogy, antiïntellectual, reëlection, и пр., которые обычно пишутся через дефис или слитно, имя Chloë, и пр.)

Чтобы показать, что е не немая, над ней может ставиться акут. (например, née, resumé, café, имя Renée, и пр.)

Чтобы показать, что c читается как s, а не k, под ней может ставиться седиль. (например, façade, и пр.)

Так что, pautinaweb, ksa, laimas, регулярное выражение будет таким... const ENGLISH_WORD_REGEXP = /([a-z]\.){2,}|\d*[a-zçéäëïöü'’‘–—-]+\d*/i;

Пример подсветки...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<section id="englishWords">
<p id="englishWordsDestination"></p>
<textarea id="englishWordsSource">Вы можете редактировать этот текст, в котором подсвечиваются английские слова. Ответственность за грамотность слов лежит на вас!

The Democrats coöperate to reëlect the President.

Stone now faces up to forty-five years in prison, on charges that he secretly coördinated with WikiLeaks and the Trump campaign on the release of Russian-hacked Democratic e-mails from the 2016 Presidential campaign and then lied to Congress about it.

Why not pretend to live in a world where North Korea is disarming, Iran is the deal-breaker, and a big, beautiful, soon-to-be-built wall is defending us from the southern invaders?

Fleitz, who served as a C.I.A. analyst for nineteen years before briefly becoming the chief of staff on Trump’s N.S.C., last year, was sticking with that line the next day.</textarea>
</section>

<style>
html, body, #englishWords, #englishWords > * {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
box-sizing: border-box;
border: 0;
}

#englishWordsDestination {
position: absolute;
color: transparent;
z-index: -1;
}

#englishWordsDestination mark {
display: inline;
color: inherit;
background: #E3F2FD;
outline: 2px solid #BBDEFB;
word-break: break-word;
}

#englishWords > * {
display: block;
resize: none;
background: transparent;
font: 1.25em / 1.5em Menlo, Consolas, monospace;
padding: 1em;
white-space: pre-wrap;
word-break: break-word;
overflow: auto;
}
</style>

<script>

const ENGLISH_WORD_REGEXP = /([a-z]\.){2,}|\d*[a-zçéäëïöü'’‘–—-]+\d*/i;

englishWordsSource.addEventListener("input", hightlightEnglishWords);

englishWordsSource.addEventListener("scroll", event => {
englishWordsDestination.scrollTop = englishWordsSource.scrollTop;
englishWordsDestination.scrollLeft = englishWordsSource.scrollLeft;
});

hightlightEnglishWords();

function hightlightEnglishWords() {
const text = englishWordsSource.value;

var s = text, m, i = 0, matchAll = [];
matchAll.input = text;

while(m = s.match(ENGLISH_WORD_REGEXP)) {
const r = Array.from(m);
r.index = i + m.index;

i += m.index + m[0].length;
matchAll.push(r);

s = s.slice(m.index + Math.max(1, m[0].length));

if(!s.length) break;
}

englishWordsDestination.textContent = "";
englishWordsDestination.appendChild(
markHighlightedWords(matchAll)
);
}

function markHighlightedWords(m) {
var i = 0;
const fragment = document.createDocumentFragment();

for(const match of m) {
fragment.appendChild(document.createTextNode(m.inp ut.slice(i, match.index)));

const highlighted = document.createElement("mark");
highlighted.textContent = m.input.slice(match.index, i = match.index + match[0].length);
fragment.appendChild(highlighted);
}

return fragment;
}

</script>
</body>
</html> Текст для примера взят из The New Yorker (https://www.newyorker.com/)

рони
18.05.2019, 07:43
Malleys,
:thanks:

рони
18.05.2019, 08:35
Malleys,
:) а может строка 77 const r = Array.from(m); лишняя?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<section id="englishWords">
<p id="englishWordsDestination"></p>
<textarea id="englishWordsSource">Вы можете редактировать этот текст, в котором подсвечиваются английские слова. Ответственность за грамотность слов лежит на вас!

The Democrats coöperate to reëlect the President.

Stone now faces up to forty-five years in prison, on charges that he secretly coördinated with WikiLeaks and the Trump campaign on the release of Russian-hacked Democratic e-mails from the 2016 Presidential campaign and then lied to Congress about it.

Why not pretend to live in a world where North Korea is disarming, Iran is the deal-breaker, and a big, beautiful, soon-to-be-built wall is defending us from the southern invaders?

Fleitz, who served as a C.I.A. analyst for nineteen years before briefly becoming the chief of staff on Trump’s N.S.C., last year, was sticking with that line the next day.</textarea>
</section>

<style>
html, body, #englishWords, #englishWords > * {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
box-sizing: border-box;
border: 0;
}

#englishWordsDestination {
position: absolute;
color: transparent;
z-index: -1;
}

#englishWordsDestination mark {
display: inline;
color: inherit;
background: #E3F2FD;
outline: 2px solid #BBDEFB;
word-break: break-word;
}

#englishWords > * {
display: block;
resize: none;
background: transparent;
font: 1.25em / 1.5em Menlo, Consolas, monospace;
padding: 1em;
white-space: pre-wrap;
word-break: break-word;
overflow: auto;
}
</style>

<script>

const ENGLISH_WORD_REGEXP = /([a-z]\.){2,}|\d*[a-zçéäëïöü'’‘–—-]+\d*/i;

englishWordsSource.addEventListener("input", hightlightEnglishWords);

englishWordsSource.addEventListener("scroll", event => {
englishWordsDestination.scrollTop = englishWordsSource.scrollTop;
englishWordsDestination.scrollLeft = englishWordsSource.scrollLeft;
});

hightlightEnglishWords();

function hightlightEnglishWords() {
const text = englishWordsSource.value;

var s = text, m, i = 0, matchAll = [];
matchAll.input = text;

while(m = s.match(ENGLISH_WORD_REGEXP)) {
s = s.slice(m.index + Math.max(1, m[0].length));
m.index += i;
i = m.index + m[0].length;
matchAll.push(m);
if(!s.length) break;
}
englishWordsDestination.textContent = "";
englishWordsDestination.appendChild(
markHighlightedWords(matchAll)
);
}

function markHighlightedWords(m) {
var i = 0;
const fragment = document.createDocumentFragment();

for(const match of m) {
fragment.appendChild(document.createTextNode(m.inp ut.slice(i, match.index)));

const highlighted = document.createElement("mark");
highlighted.textContent = m.input.slice(match.index, i = match.index + match[0].length);
fragment.appendChild(highlighted);
}

return fragment;
}

</script>
</body>
</html>

laimas
18.05.2019, 10:00
Чтобы показать, что гласная буква образует отдельный слог, над ним может ставиться умляут.

Ага, больному собрались делать сложнейшую операцию, а на поверку оказалось, что у него насморк. ;)

Хрен знает, что нужно найти, какие сочетания, и только "если", тогда на все случаи. Спросите у автора, мне в общем то все равно, хватит ли ему от ksa или же нужно все учитывать.

laimas
21.05.2019, 05:28
Malleys, так получилось, что тут.

Суть вопроса ясна, но он все таки из разряда "скажите, а в какой понедельник будет среда?". Поэтому и ответ может быть "либо в четверг, либо в пятницу".

Ну ежику же известно, что так искать слова на странице, это накладно т.к. даже в body много будет того среди чего искать не стоит. Следовательно нужно уточнение, чтобы сузить область поиска. А исходя из этого можно и предположить, что нужно вообще найти банальное, типа ссылок, а вопрос поставлен так по незнанию. И надо ли заморачиваться умляутами и прочим может быть известно только при вопросе раскрывающем задачу в полной мере.

Вот почему мне как-то все равно, чего будет достаточно в данном случае.