# Pattern\_replace not working with optional regex

**URL:** <https://discuss.elastic.co/t/pattern-replace-not-working-with-optional-regex/90365>\
**Category:** Elasticsearch\
**Created:** [June 21, 2017, 9:13pm UTC](https://discuss.elastic.co/t/pattern-replace-not-working-with-optional-regex/90365 "2017-06-21T21:13:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![marcy-buccellato](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/marcy-buccellato/32/18728_2.png) [@marcy-buccellato](https://discuss.elastic.co/u/marcy-buccellato)\
**Post date:** [June 21, 2017, 9:13pm UTC](https://discuss.elastic.co/t/pattern-replace-not-working-with-optional-regex/90365/1 "2017-06-21T21:13:07Z")

</div>

I'm trying to remove `http://` and/or `www` from a url, as well as `?...`, so basically strip it to it's minimal form. I'm using the [`pattern_replace` `char_filter`](https://www.elastic.co/guide/en/elasticsearch/reference/1.7/analysis-pattern-replace-charfilter.html) (ES version 1.7). And having trouble matching "optional" regex pattern:

So here's my filter:

```auto
"url_strip_filter": {
	"type": "pattern_replace",
	"pattern": "(?:http:\\/\\/)?(?:www\\.)?([^\\?]+)(?:\\?.*)?",
	"replacement": "$1"
}

```

And when I use the ES `_analayze` endpoint for that filter, it is not stripping out the optional groups:

```auto
GET /my_index/_analyze?char_filters=url_strip_filter&tokenizer=keyword
{
    "text": "http://www.blah.com/?foo"
}

{
   "tokens": [
      {
         "token": "{\n \"text\": \"http://www.blah.com/\n}\n",
         "start_offset": 0,
         "end_offset": 43,
         "type": "word",
         "position": 1
      }
   ]
}

```

But when I remove the `?` for optional, it works:

```auto
"url_strip_filter": {
	"type": "pattern_replace",
	"pattern": "(?:http:\\/\\/)(?:www\\.)([^\\?]+)(?:\\?.*)?",
	"replacement": "$1"
}

{
   "tokens": [
      {
         "token": "{\n \"text\": \"blah.com/\n}\n",
         "start_offset": 0,
         "end_offset": 43,
         "type": "word",
         "position": 1
      }
   ]
}

```

I don't _think_ it's a regex issue bc I tested the regex and it works as expected: [https://regex101.com/r/Hd9E2V/3](https://regex101.com/r/Hd9E2V/3).

Not sure what I'm missing here, but any help would be appreciated!

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 19, 2017, 9:13pm UTC](https://discuss.elastic.co/t/pattern-replace-not-working-with-optional-regex/90365/2 "2017-07-19T21:13:09Z")

</div>

Closed on July 19, 2017, 9:13pm UTC

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
