annad

annad

Regular expression required to split a string into parts to bold what the user has entered

After wasting 30 minutes trying to refine a request on two AI engines (including ChatGPT), I’m less worried about AI taking over the world. :roll_eyes: Wondering if a human could help me come up with a regular expression that will work for my needs.

I have your basic Type-to-Select component. I just want to split a string into parts so that I can bold what the user has entered. I need a regular expression to use with String.split/3.Here’s the result I’m looking for.

  • There is a search_string and an input_string.
  • If the search_string is found at the beginning or end of the input_string, then I’d get 2 parts from String.split/3
  • If the search_string is found in the middle of the input_string, then I’d get a maximum of 3 parts from String.split/3.
  • It needs to be case-insensitive

For example:

search_string: "san"
input_string: "San Francisco, California, US"

I would get two parts: ["San", " Francisco, California, US"]
NOTE: Spaces need to be preserved for when I join it back together

search_string: "fran"

produces 3 parts: ["San ", "Fran", "cisco, California, US"]

search_string: "US"

produces 2 parts: ["San Francisco, California, ", "US"]

Marked As Solved

al2o3cr

al2o3cr

This will satisfy all the requirements you listed, but it has bugs (see below):

String.split(input_string, ~r{#{search_string}}i, trim: true, include_captures: true)
  • trim: true ensures that a match at the start of a string doesn’t produce a leading ""
  • include_captures: true puts the matches in the output

The first bug is that metacharacters in search_string will be interpreted normally, so searching for . splits the string into individual characters. This can be fixed with Regex.escape:

String.split(input_string, ~r/#{Regex.escape(search_string)}/i, trim: true, include_captures: true)

The second bug is that a repeated match will split into more fields:

search_string = "a"

produces ["S", "a", "n Fr", "a", "ncisco, C", "a", "liforni", "a", ", US"]

Setting parts can help, but has corner-cases with matches at the beginning / end.


A way to avoid that second bug is to write a regex with exactly what you mean:

Regex.run(~r/^(.*)(#{Regex.escape(search_string)})(.*)$/i, input_string, capture: :all_but_first)

This will require some cleanup for the leading + trailing cases, since .* can match "".

Also Liked

joelpaulkoch

joelpaulkoch

Do you absolutely need to solve it with a regex? Couldn’t you try pattern matching instead and then split accordingly?

dimitarvp

dimitarvp

:exclamation:OFF-TOPIC::exclamation:

I am willing to bet $50 that within 24 hours somebody is going to post this to Reddit or 9GAG. :003:

I really was not prepared to burst out laughing on the first post I see on ElixirForum today.

annad

annad

That works great! I tested it on some of the cities with long names and special characters and it broke it up into correct parts. You’re right in that some parts are empty strings, but I just Enum.filter those out.

One of my previous regex expressions was doing exactly what you described in the second bug. It was breaking the string into a part for every letter. Your suggestion works perfectly. Thank you so much!

AI: 0 Human: 1
Not that I’m keeping score. :smile:

annad

annad

Here is the final code for anyone else trying to bold just part of a string based on user input. Please see “Solution” above by @al2o3cr for explanation of the regular expression.

defp matches?(search_result, input) do
    String.contains?(String.downcase(search_result), String.downcase(input))
  end

  defp format_search_result(display_string, input) do
    if matches?(display_string, input) do
        Regex.run(~r/^(.*)(#{Regex.escape(input)})(.*)$/i, display_string, capture: :all_but_first)
        |> Enum.filter(&(&1 != ""))
        |> Enum.map(fn part ->
              if String.match?(part, ~r/#{Regex.escape(input)}/i ) do
                "<strong>#{part}</strong>"
              else part end
           end)
        |> Enum.join()
    else
      display_string
    end
  end

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement