Match any part of the word

For example, with a line like previous, I want the pattern to match the lines p, pr, pre, prev, etc., all the way up to previous. I do NOT want it to match lines like prevalent or previse.
Is there a pattern to accomplish this aside from the obvious (^(p|pr|pre|prev|...|previous)$)?

Note: I do not need to capture it like in the above pattern, and
I’m using Perl’s regular expression flavor (in Perl).

nhahtdh's user avatar

nhahtdh

55.7k15 gold badges125 silver badges162 bronze badges

asked Jul 19, 2011 at 12:42

Brandon Coffman's user avatar

Brandon CoffmanBrandon Coffman

2441 gold badge2 silver badges9 bronze badges

4

/^p(r(e(v(i(o(u(s)?)?)?)?)?)?)?$/

And just to double check that it works:

for (qw/p pr pre previous prevalent previse/) {
    $result = (/^p(r(e(v(i(o(u(s)?)?)?)?)?)?)?$/? "yes" : "no");
    print "Checking $_: $resultn";
}

Produces:

Checking p: yes
Checking pr: yes
Checking pre: yes
Checking previous: yes
Checking prevalent: no
Checking previse: no

answered Jul 19, 2011 at 12:45

Adam Batkin's user avatar

Adam BatkinAdam Batkin

51.2k8 gold badges125 silver badges115 bronze badges

7

I don’t think regex is the best (or most readable) way to do this:

$str = "previous";
$input = "prev";
$length = length($input);

$strcheck = substr($str, 0, $length);
$incheck = substr($input, 0, $length);

if ($strcheck =~ $incheck && $length != 0) {
    // do something with $input
}

answered Jul 19, 2011 at 15:29

NorthGuard's user avatar

#!/usr/bin/perl
use strict;
use warnings;

my $string = "previous"; 
my @array = split //,$string;

chomp(my $input=<STDIN>); #take the input from the user
my @array2 = split //,$input;

my $i=0;

foreach (@array2){
        if($_ eq $array[$i]){
            print "$_ matchedn";
        }
$i++;
}

answered Jul 19, 2011 at 17:32

Chankey Pathak's user avatar

Chankey PathakChankey Pathak

21k12 gold badges85 silver badges133 bronze badges

Match the parts of the words.
e.g. ward D
1. bed
2. out
3. coffee
4. arm
5. wash
6. fire
7. down
8. book
↓↑

A. table


B. stairs


C. room


D. robe


E. side


F. basin


G. chair


H. case


I. place

reshalka.com

Английский язык 5 класс (Test Booklet) Spotlight Английский в фокусе Ваулина. TEST 3 A (Module 3). Номер №A

Решение

Перевод задания
Составь части слов.
e.g. ward D
1. bed
2. out
3. coffee
4. arm
5. wash
6. fire
7. down
8. book
↓↑

A. table


B. stairs


C. room


D. robe


E. side


F. basin


G. chair


H. case


I. place

 
ОТВЕТ
1 – С. bedroom
2 – E. outside
3 – A. coffee table
4 – G. armchair
5 – F. washbasin
6 – I. fireplace
7 – B. downstairs
8 – H. bookcase

 
Перевод ответа
1 − С. спальня
2 − E. снаружи
3 − А. журнальный столик
4 − G. кресло
5 − F. умывальник
6 − I. камин
7 − B. внизу
8 − H. книжный шкаф

I’ve been trying to get a specific regex working but I can’t get it to do what I need.

Basically, I want it to look for ROCKET. The regex should match ROCKET in upper or lower cases, and with or without punctuation, but not when part of another word. So, the regex would trigger on any of these:

rocket
RoCKEt
hi Rocket
This is a rocket.
ROCKET's engine

but NOT trigger on ROCKET when it is found in something like

Rocketeer
Sprocket

I’ve been trying to get it right using a regex generator online but I can’t get it to match exactly.

asked Apr 18, 2015 at 17:16

Kefka's user avatar

1

I suggest bookmarking the MSDN Regular Expression Quick Reference

you want to achieve a case insensitive match for the word «rocket» surrounded by non-alphanumeric characters. A regex that would work would be:

W*((?i)rocket(?-i))W*

What it will do is look for zero or more (*) non-alphanumeric (W) characters, followed by a case insensitive version of rocket ( (?i)rocket(?-i) ), followed again by zero or more (*) non-alphanumeric characters (W). The extra parentheses around the rocket-matching term assigns the match to a separate group. The word rocket will thus be in match group 1.

UPDATE 1:
Matt said in the comment that this regex is to be used in python. Python has a slightly different syntax. To achieve the same result in python, use this regex and pass the re.IGNORECASE option to the compile or match function.

W*(rocket)W*

On Regex101 this can be simulated by entering «i» in the textbox next to the regex input.

UPDATE 2 Ismael has mentioned, that the regex is not quite correct, as it might match «1rocket1». He posted a much better solution, namely

(?:^|W)rocket(?:$|W)

answered Apr 18, 2015 at 17:32

Xaser's user avatar

XaserXaser

7862 gold badges10 silver badges18 bronze badges

19

I think the look-aheads are overkill in this case, and you would be better off using word boundaries with the ignorecase option,

brocketb

In other words, in python:

>>> x="rocket's"
>>> y="rocket1."
>>> c=re.compile(r"brocketb",re.I)  # with the ignorecase option
>>> c.findall(y)
[]
>>> c.findall(x)
['rocket']

answered Apr 19, 2015 at 6:17

beroe's user avatar

beroeberoe

1,1377 silver badges18 bronze badges

2

With grep and sed, you can use <rocket>
With grep, the -i option will make it case-insensitive (ignore case):

grep -i '<rocket>'

I don’t know any way to make all sed regexes case-insensitive,
but there’s always the caveman way:

sed -n '/<[Rr][Oo][Cc][Kk][Ee][Tt]>/p'

answered Apr 19, 2015 at 4:00

Scott - Слава Україні's user avatar

Use the Search for whole words only option.

As far as punctuations, you can’t answer it till you know the flavour/flavor.

It’s a very old thread, so posted for someone who might visit with a need, later. Ones who originated the thread might have moved to something else… No?

answered Nov 23, 2019 at 10:06

Rex Schweiss's user avatar

1

I think you can use something like this to specific your word that you want:
/^(rocket|RoCKEt)$/g

answered Mar 4, 2021 at 10:14

Techit Kakaew's user avatar

1

For online regex generators(if the text is constant):

/brocketb/gi

And if you need to use a variable in a regular expression, then:
Ex.:

let inputStr = "I need to check the following text: rocket RoCKEt hi Rocket This is a rocket. ROCKET's engine Rocketeer Sprocket";

let replaceThis = "ROCKET";
let re = new RegExp(`\b${replaceThis}\b`, 'gi');
console.log(inputStr.replace(re, "******")); // "I need to check the following text: ****** ****** hi ****** This is a ******. ******'s engine Rocketeer Sprocket"

answered May 25, 2021 at 11:37

Kishor's user avatar

KishorKishor

1012 bronze badges

I don’t have enough reputation to comment, so I have to make a post to share why I think the user beroe’s solution is the best way to do this problem.
Take for example this string of text from the codewars challenge Most frequently used words in a text:

a a a b c c d d d d e e e e e

The goal of this challenge is to count the occurrences of words in the text.
If we go with the most popular solution:

(?:^|W)rocket(?:$|W)

in our string of text if we search for ‘a’ instead of ‘rocket’ using re.findall for python it will only return two matches (the first and last a), since the W capture overlaps the middle a from matching. Using b for the word barrier on the other hand returns all 3 a’s as matches

brocketb

Agian, credit to user beroe’s solution above

answered May 13, 2022 at 4:16

Rob R's user avatar

3

olegstatsenko2002

olegstatsenko2002

Complete the lists with the correct word.

Example: sixty, seventy, eighty, ninety.

one hundred   one thousand   ninety

1   Tuesday, Wednesday, Thursday, _Friday_________.

     Saturday   Friday   Monday

2   fifty-seven, fifty-eight, fifty-nine, _sixty_________.

     sixty   forty   seventy

3   Sunday, Monday, Tuesday, ___Wednesday_______.

     Wednesday   Friday   Thursday

4   fifteen, twenty, twenty-five, __thirty________.

     thirty-five   thirteen   thirty

5   seven, eight, nine, ___ten_______.

     eleven   ten   twelve

6   two, four, six ___eight_______.

     nine   eight   ten

6

6   Complete the chart.

Example:    Brazil   Brazilian

1   _ Germany_______  German

2   France             __French________

3   The United States_________       American

4    China            ___Chinese_______

5   _ Italy_______        Italian

6   _ Japan_________    Japanese

6

Vocabulary total

20

PRONUNCIATION

7   Underline the stressed syllable.

Example:    coffee

1   toilet   toilet

2   Internet  internet

3   pizza   pizza

4   computer   computer

5   airport   airport

​​​​​​​

Ребят помогите не понимаю !

Match the parts of the words and make up 10 compounds.

When.

Black.

Down.

Home.

Up. Work.

Ever.

Stairs

Board.

Mate

Arm

Side

Chair

Cup

Sea

Class

Board

Ever

Where

Stairs

Помогите!

На этой странице находится вопрос Ребят помогите не понимаю ?. Здесь же – ответы на него,
и похожие вопросы в категории Английский язык, которые можно найти с помощью
простой в использовании поисковой системы. Уровень сложности вопроса
соответствует уровню подготовки учащихся 5 — 9 классов. В комментариях,
оставленных ниже, ознакомьтесь с вариантами ответов посетителей страницы. С
ними можно обсудить тему вопроса в режиме on-line. Если ни один из
предложенных ответов не устраивает, сформулируйте новый вопрос в поисковой
строке, расположенной вверху, и нажмите кнопку.

Like this post? Please share to your friends:
  • Match and vlookup in excel
  • Match a single word with a synonym phrase prospects promoted retired
  • Match a question word in a and an answer in b
  • Match a column in excel
  • Match and make up sentences with these word