Find the end of each word

I have a small problem with Regular Expressions ( regex ).

I want to remove any «T» at the end of each word in the string.
This is the code I am using to display all the words ending with «T».

public static void main (String []args){
    String name = "PHYLAURHEIMSMET hello tttttyyuolktttb fedqs jhgjt";
    p = Pattern.compile("([a-z0-9]+)?[t]");
    m = p.matcher(s);

    while (m.find()) {
        System.out.println(m.group());
    }
}

Thank you for all your help.

Andrew Spencer's user avatar

asked Jun 3, 2015 at 9:06

yougho's user avatar

3

i try to remove any «T» at the end of each word

string.replaceAll("T(?!\S)", "");

This would match all the T‘s which was present at the end of each word.

OR

string.replaceAll("T(?=\s|$)", "");

This would match all the t‘s only if it’s follwed by a space or end of the line anchor.

To do a case-insensitive replacement.

string.replaceAll("(?i)T(?!\S)", "");

DEMO

answered Jun 3, 2015 at 9:08

Avinash Raj's user avatar

Avinash RajAvinash Raj

171k27 gold badges227 silver badges271 bronze badges

13

I would use the b word-boundary to test if the letter is at the end of the word, you can see the result of replacing tb with an empty string on this regex101.

I’m not sure if you want to only remove upper case T’s, in that case, remove the i all the way to the right.

In Java that would be:

string.replaceAll("Tb", ""); // <-- only upper case T's
string.replaceAll("(?i)Tb", ""); // <-- both t and T's

answered Jun 3, 2015 at 9:18

asontu's user avatar

asontuasontu

4,5081 gold badge20 silver badges29 bronze badges

3

This is just suggetion why not to use simple String class inbuilt functions something like this :

String name = "PHYLAURHEIMSMET hello tttttyyuolktttb fedqs jhgjt";
        if ('t' == name.charAt(name.length() - 1) || 'T' == name.charAt(name.length() - 1)) {
            System.out.println("contains last char 't' or 'T'");
        }

answered Jun 3, 2015 at 9:19

Prashant's user avatar

PrashantPrashant

4,4347 gold badges34 silver badges81 bronze badges

Use the word given in capitals at the end of each line to form a word that fits each space.
1. How can I stop making _ mistakes in my exam? CARE
2. Her sister is _ songwriter. SUCCESS
3. I don’t know what to say! I’m _ . SPEECH
4. Mr Buxton is such a kind and _ man. THOUGHT
5. Be _ ! There’s a banana skin on the road. CARE

reshalka.com

Английский язык 7 класс рабочая тетрадь Spotlight Английский в фокусе Ваулина. 7c. In the charts!. Номер №2

Решение

Перевод задания
Используйте слово, указанное заглавными буквами в конце каждой строки, чтобы сформировать слово, подходящее для каждого пробела.
1. Как мне перестать делать _ ошибок на экзамене? ЗАБОТА
2. Ее сестра _ автор песен. УСПЕХ
3. Я не знаю, что сказать! Я _ . РЕЧЬ
4. Мистер Бакстон такой добрый и _ человек. МЫСЛЬ
5. Будьте _! На дороге валяется банановая кожура. ЗАБОТА

ОТВЕТ
1. How can I stop making careless mistakes in my exam?
2. Her sister is successful songwriter.
3. I don’t know what to say! I’m speechless.
4. Mr Buxton is such a kind and thoughtful man.
5. Be careful! There’s a banana skin on the road.

Перевод ответа
1. Как мне перестать делать ошибки по неосторожности на экзамене?
2. Ее сестра − успешный автор песен.
3. Я не знаю, что сказать! У меня нет слов.
4. Мистер Бакстон такой добрый и внимательный человек.
5. Будьте осторожны! По дороге банановая кожура.

veforeve

veforeve

Вопрос по английскому языку:

Use the word given in capitals at the end of each line to form a word that fits each space
1)LERN.COM is a great … website (EDUCATION)
2)this teacher taught us a lot about (CONSERVE)
3) my father works as a (REPORT)
4)there was a big … in the city center today. (DEMONSTRATE)
Помогите срочно

Трудности с пониманием предмета? Готовишься к экзаменам, ОГЭ или ЕГЭ?

Воспользуйся формой подбора репетитора и занимайся онлайн. Пробный урок — бесплатно!

Ответы и объяснения 1

howrive

howrive

1. This teacher taught us a lot about conservation. (Этот учитель многому нас научил о сохранении). 2. LEARN.COM is a great educational website. (LEARN.COM — отличный образовательный вебсайт). 3. My father works as a reporter. (Мой папа работает журналистом.)4. There was a big demonstration in the city centre today. (В центре города сегодня была большая демонстрация)

Знаете ответ? Поделитесь им!

Гость

Гость ?

Как написать хороший ответ?

Как написать хороший ответ?

Чтобы добавить хороший ответ необходимо:

  • Отвечать достоверно на те вопросы, на которые знаете
    правильный ответ;
  • Писать подробно, чтобы ответ был исчерпывающий и не
    побуждал на дополнительные вопросы к нему;
  • Писать без грамматических, орфографических и
    пунктуационных ошибок.

Этого делать не стоит:

  • Копировать ответы со сторонних ресурсов. Хорошо ценятся
    уникальные и личные объяснения;
  • Отвечать не по сути: «Подумай сам(а)», «Легкотня», «Не
    знаю» и так далее;
  • Использовать мат — это неуважительно по отношению к
    пользователям;
  • Писать в ВЕРХНЕМ РЕГИСТРЕ.

Есть сомнения?

Не нашли подходящего ответа на вопрос или ответ отсутствует?
Воспользуйтесь поиском по сайту, чтобы найти все ответы на похожие
вопросы в разделе Английский язык.

Трудности с домашними заданиями? Не стесняйтесь попросить о помощи —
смело задавайте вопросы!

Английский язык — язык англо-фризской подгруппы западной группы германской ветви индоевропейской языковой семьи.

Simple Pig Latin

Move the first letter of each word to the end of it, then add «ay» to the end of the word. Leave punctuation marks untouched.

Examples

pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !')     # elloHay orldway !

def pig_it(text):

    words=text.split(» «)

    op=[]

    punct=»’!()-[]{};:'»,<>./?@#$%^&*_~»’

    for word in words:

        if word in punct:

            op.append(word)

        else:

            res=word[1:]+word[0]+»ay»

            op.append(res)

    return » «.join(op)

0
Comments

Выполнить задание.
Use the word given in capitals at the end of each line to form a word that fits in the gap in the same line.
Qualcomp Powertop
Qualcomp have just brought out their (1) ……………….. new handheld computer, the Powertop. It’s (2) ………………. not to love it, with its smooth, shiny (3) .„, ……………. and its bright screen. It might not be the best (4) …………………..to handheld computing because it is quite advanced, but you’ll find an (5) ……………….. of all the features in the detailed manual. The Powertop has been (6) ………………… designed to fit a lot of computing
power in your palm. The (7) ………………. of a unique wireless Internet
connection means there’s a world of (8) ……………….. just waiting for you. We give the Powertop nine out often.

Слова которые нужно вставить вместо цифр.
REVOLUTION, POSSIBLE, APPEAR, INTRODUCE, EXPLAIN, SCIENCE, INVENT, DISCOVER

The challenge

Move the first letter of each word to the end of it, then add “ay” to the end of the word. Leave punctuation marks untouched.

Examples

pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !')     # elloHay orldway !

Test cases

Test.assert_equals(pig_it('Pig latin is cool'),'igPay atinlay siay oolcay')
Test.assert_equals(pig_it('This is my string'),'hisTay siay ymay tringsay')

How to write the code in Python

def pig_it(text):
    words = text.split(" ")
    
    new_words = []
    
    for word in words:
        if word.isalpha():
            new_word = word[1:] + word[0] + "ay"
            new_words.append(new_word)
        else:
            new_words.append(word)
        
        
    return " ".join(new_words)
    

Понравилась статья? Поделить с друзьями:
  • Find the odd word in the chain of the nouns trousers spectacles
  • Find the duplicates in excel
  • Find the odd word in the chain of the nouns tea butter onions meat
  • Find the definition of this word to fail
  • Find the odd word in each line and cross it out ответы