Matching multiple substrings to a string

check if multiple substrings in string
python extract multiple substrings from string
multiple string contains in python
find all substrings in string python
python search string multiple substrings
check if multiple strings in string
find substring in string python
python in string multiple

I have an application where the user types in text, then this text is sent to the server and it returns an array of words that contain this text.

But as you can see the problem starts when there are more then 1 match. Here's my current code:

state.input !== '' && vocabularyItems && (, index) => {
      const regex = new RegExp(input, 'gi');
      const results = vocabularyItem.matchAll(regex);

      const tmp = [];
      for (const match of results) {
        let currentLoop = vocabularyItem.slice(0, match.index);

        currentLoop += '<strong className="tt-highlight">';

        currentLoop += vocabularyItem.slice(match.index, match.index + input.length);

        currentLoop += '</strong>';

        currentLoop += vocabularyItem.slice(match.index + input.length, vocabularyItem.length);


      return (
          className={`override-strong tt-suggestion tt-selectable ${cursor === index && 'tt-cursor'}`}
          dangerouslySetInnerHTML={{ __html: tmp }}

and here are some examples in HTML code

<strong className="tt-highlight">En</strong>kelkind

<strong className="tt-highlight">En</strong>gagement
Engagem<strong className="tt-highlight">en</strong>t

as you can see, it works when there is only one occurence, but duplicates the word when more then one match is present. How can I end up with just something like



I forgot to add that I need the case preserved

First off, I would recommend to use, something, like:

const results = vocabularyItems.filter(word => word.toLowerCase().includes(input.toLowerCase()))

for case insensitive vocabulary lookup.

Next, I would highlight the match in a bit different way. I'd split suggested option into parts (matching search input and non-matching ones) , then style those respectively:

const parts = suggestion.split(new RegExp(`(?=${match})|(?<=${match})`, 'gi'))
...,key) => {
          const style = part.toLowerCase() == match.toLowerCase() ? 'bold' : 'normal'
          return <span style={{fontWeight:style}} {...{key}}>{part}</span>

I think it's safe enough to assume that you build autocomplete search input, thus you might find of use the quick demo below (excluding all the styling):

const { render } = ReactDOM,
      { useState } = React

const vocabulary = ['engagement', 'Bentley', 'English', 'seven', 'Engagement']

//suggested option component
const SuggestedOption = ({suggestion, match}) => {
  const parts = suggestion.split(new RegExp(`(?=${match})|(?<=${match})`, 'gi'))
  return (
      {,key) => {
          const style = part.toLowerCase() == match.toLowerCase() ? 'bold' : 'normal'
          return <span style={{fontWeight:style}} {...{key}}>{part}</span>

//autocomplete component
const SearchBar = () => {
  const [suggestions, setSuggestions] = useState([]),
        [inputValue, setInputValue] = useState(''),
        onInput = input => {
          setSuggestions(vocabulary.filter(word => input.length && word.toLowerCase().includes(input.toLowerCase())))
  return (
      <input onKeyUp={e => onInput(} />
      <div >
,key) => <SuggestedOption {...{key,suggestion,match:inputValue}} />)

  <SearchBar />,
<script src=""></script><script src=""></script><div id="root"></div>

Check If a String Contains Multiple Keywords, For that, we'll use the Pattern class. First, let's define the string expression. As we need to match two keywords, we'll build our regex rule with� In computer science, string-searching algorithms, sometimes called string-matching algorithms, are an important class of string algorithms that try to find a place where one or several strings (also called patterns) are found within a larger string or text.

Here's a way to do it with string.replace:

const list = [

const boldify = (search) => {
  return (string) =>
    string.replace(new RegExp(search, 'gi'), '<strong>$&</strong>')

document.body.innerHTML ='en')).join('<br>')

Check if multiple strings exist in another string : Python, Here the script return "Found a match", because at least one word exists in the list . example 2: myList = ['one', 'six','ten'] str = "one two three four five" isMatch =� :param str string: string to execute replacements on :param dict replacements: replacement dictionary {value to find: value to replace} :rtype: str """ # Place longer ones first to keep shorter substrings from matching # where the longer ones should take place # For instance given the replacements {'ab': 'AB', 'abc': 'ABC'} against # the string

EDIT - Yevgen's answer is much nicer than this one.

A simple loop can achieve this if i understand correctly what you want:

var array = ["end","engagement","Engagement","england","enough","not this","or this"];

function filterArray(array, id) {
    var returnArray = [];
  for (var i = 0; i < array.length; i++) {
    value = array[i];
    if (value.includes(id)) {
    return returnArray;

var filteredArray = filterArray(array,"en");

If you wanted to ensure duplicates (where case on Engagement causes a duplicate) you could set the string to lowercase before pushing to the array, and check the array for the existence of the string before pushing again.

How to check for multiple substrings in a string in Python, Use a for loop to iterate through a list of substrings. Within the for loop, check if each substring is in the string using the in keyword syntax substring in string� Longest palindromic string possible after removal of a substring; Convert camel case string to snake case in Java; Count of binary strings of length N having equal count of 0's and 1's and count of 1's ≥ count of 0's in each prefix substring; Find strings that end with a given suffix; Reverse the substrings of the given String according to

14 Strings, Multiple strings are often stored in a character vector, which you can create with Once you've mastered pattern matching, you'll learn how to apply those ideas� Abstracting multiple pattern match criteria to CSV files. You may want to store multiple string matching criteria in a separate CSV file rather than directly in the code. Let’s create a CSV that matches all strings that start with coffee, end with bread or contain nice|person. Here’s the content of the random_matches.csv file.

Find strings that contain multiple substrings at the same time , Find strings that contain multiple substrings at Learn My strings are: 'First Example','Second Example', 'Third Example' %compare invested market value. For instance, to get the last 4 characters from the end of a string, use this formula: =RIGHT(A2,4) Extract text from middle of string (MID) If you are looking to extract a substring starting in the middle of a string, at the position you specify, then MID is the function you can rely on.

How to check if multiple strings exist in another string in Python?, To check if any of the strings in an array exists in another string, you 'o', 'u'] str = "hello people" if any(c in str for c in arr): print "Found a match"� Check if string contains another string in Swift; How to check if a substring is contained in another string in Python; How to check if multiple elements with same class exist using jQuery? How to check if a string is a subset of another string in R? How to check if a column exist in a MySQL table? How to check if a String contains another

  • How would you extend this to prevent Engagement and engagement appearing twice?
  • I forgot to add that I need the case to be preserved
  • if the server responds with Engagement i need to highlight it like <strong>En</strong>gagem<strong>en</strong>t. This is under the condition that the user typed in en, or En
  • It returns whatever it finds in the db
  • Ok I probably did something wrong. Where should I use this code?
  • What is the $& in the strong?
  • Inserts the matched substring,…
  • Taking into account reactjs tag, I think, with this approach (that is very similar to the one I've suggested at first) it may be difficult to render modified string within React component, as it will render part of a string enclosed within <strong> tag as [Object][object]. I came across that problem while preparing live-demo for my answer so I switched to another one.
  • @YevgenGorbunkov indeed your solution is more thorough. I didn't even see the reactjs tag and went for a first step solution that OP would have to enhance to his desire :) I'll still let my solution here, guessing that it may interest one for a quick solution! But of course I do not recommand generating HTML with text strings.
  • @YevgenGorbunkov I've updated my answer, this version is blazing fast and I thought you would like to see it :)
  • pushing lowercased words into suggestions array wouldn't appear very nice for items like English, I'd rather suggest to keep case untouched, though it may eat up performance a bit. You may check out example over here (lines 29 through 34, test keywords 'Engagement' and 'seven').