---
title: "Freemarker 字符串使用正则表达式替换"
author: "buddie"
date: "2019-12-20T17:17:31Z"
tags: []
categories: ["Web前端"]
slug: "freemarker"
draft: false
lastmod: "2019-12-20T17:17:31Z"
id: 2511253
url: "https://buddie.iteye.com/blog/2511253"
---

## 目的

在Freemarker模板中，使用replace方法，将链接的域名去掉 比如“[http://www.buddie.cn/ab/cd”或“https://192.168.1.1:8080/ab/cd”，都处理为“/ab/cd”](http://www.buddie.cn/ab/cd%E2%80%9D%E6%88%96%E2%80%9Chttps://192.168.1.1:8080/ab/cd%E2%80%9D%EF%BC%8C%E9%83%BD%E5%A4%84%E7%90%86%E4%B8%BA%E2%80%9C/ab/cd%E2%80%9D)

## 实现

```
${url?replace('http[s]?://[\\w\\.:\\d]*','','ri')}
```

主要是replace的第三个参数，要加r，用于开始正则表达式模式

## 参考文档

[https://freemarker.apache.org/docs/ref\_builtins\_string.html#ref\_builtin\_string\_flags](https://freemarker.apache.org/docs/ref_builtins_string.html#ref_builtin_string_flags) 

[https://freemarker.apache.org/docs/gloss.html#gloss.regularExpression](https://freemarker.apache.org/docs/gloss.html#gloss.regularExpression)