Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a new filter: regex_extract #3220

Merged
merged 2 commits into from Feb 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.md
Expand Up @@ -2,6 +2,7 @@

| DateOfChange | Changes |
|----------------|--------------------------------------------------------------------------------------------------------------|
| Feb 19, 2023 | Add a new Liquid filter named `regex_extract`. [3220](https://github.com/huginn/huginn/pull/3220) |
| Feb 18, 2023 | Fix permissions on /app in the Docker images. [3218](https://github.com/huginn/huginn/pull/3218) |
| Feb 06, 2023 | BoxcarAgent is removed; the service is long gone. |
| Dec 15, 2022 | DataOutputAgent Add dc namespace option. [3189](https://github.com/huginn/huginn/pull/3189) |
Expand Down
6 changes: 6 additions & 0 deletions app/concerns/liquid_interpolatable.rb
Expand Up @@ -231,6 +231,12 @@ def to_xpath(string)
end
end

def regex_extract(input, regex, index = 0)
input.to_s[Regexp.new(regex), index]
rescue Index
nil
end

def regex_replace(input, regex, replacement = nil)
input.to_s.gsub(Regexp.new(regex), unescape_replacement(replacement.to_s))
end
Expand Down
16 changes: 16 additions & 0 deletions spec/concerns/liquid_interpolatable_spec.rb
Expand Up @@ -228,6 +228,22 @@ def @filter.to_xpath_roundtrip(string)
end
end

describe 'regex_extract' do
let(:agent) { Agents::InterpolatableAgent.new(name: "test") }

it 'should extract the matched part' do
agent.interpolation_context['something'] = "foo BAR BAZ"
agent.options['test'] = "{{ something | regex_extract: '[A-Z]+' }} / {{ something | regex_extract: '[A-Z]([A-Z]+)', 1 }} / {{ something | regex_extract: '(?<x>.)AZ', 'x' }}"
expect(agent.interpolated['test']).to eq("BAR / AR / B")
end

it 'should return nil if not matched' do
agent.interpolation_context['something'] = "foo BAR BAZ"
agent.options['test'] = "{% assign var = something | regex_extract: '[A-Z][a-z]+' %}{% if var == nil %}nil{% else %}non-nil{% endif %}"
expect(agent.interpolated['test']).to eq("nil")
end
end

describe 'regex_replace' do
let(:agent) { Agents::InterpolatableAgent.new(name: "test") }

Expand Down