[英]Using regex to find chars in a string and replace
When returning a string value from an incoming request in my network based app, I have a string like this 'post http://a.com\\r\\nHost: a.com\\r\\n'
从基于网络的应用程序中的传入请求返回字符串值时,我有这样的字符串
'post http://a.com\\r\\nHost: a.com\\r\\n'
Issue is that the host is always changing so I need to replace it with my defined host. 问题是主机总是在变化,因此我需要用定义的主机替换它。 To accomplish that I tried using regex but am stuck trying to find the
'host:a.com'
chars in the string and replacing it with a defined valued. 为了实现这一点,我尝试使用正则表达式,但是在尝试在字符串中查找
'host:a.com'
字符并将其替换为定义的值时遇到了麻烦。
I tried using this example www.javamex.com/tutorials/regular_expressions/search_replace_loop.shtml#.VUWvt541jqB changing the pattern compile to : ([\\\\d]+)
but it still remains unchanged. 我尝试使用此示例www.javamex.com/tutorials/regular_expressions/search_replace_loop.shtml#.VUWvt541jqB将模式编译更改为:
([\\\\d]+)
但仍保持不变。
My goal is to replace given chars in a string with a defined value and returning the new string with the defined value. 我的目标是使用定义的值替换字符串中的给定字符,并使用定义的值返回新字符串。 Any pointers?
有指针吗?
EDIT : Sample of a typical incoming request: Post http://example.com\\r\\nHost: example.com\\r\\nConnection: close\\r\\n
编辑 :典型的传入请求的示例:
Post http://example.com\\r\\nHost: example.com\\r\\nConnection: close\\r\\n
Another incoming request might take this form: GET http://example2.net\\r\\nContent-Length: 2\\r\\nConnection: close\\r\\nHost: example2.net\\r\\n
另一个传入请求可能采用以下形式:
GET http://example2.net\\r\\nContent-Length: 2\\r\\nConnection: close\\r\\nHost: example2.net\\r\\n
I want to replace it to this forms Post http://example.com\\r\\nHost: mycustomhostvalue.com\\r\\nConnection: close\\r\\n
我想将其替换为以下形式
Post http://example.com\\r\\nHost: mycustomhostvalue.com\\r\\nConnection: close\\r\\n
GET http://example2.net\\r\\nContent-Length: 2\\r\\nConnection: close\\r\\nHost: mycustomhostvalue.com\\r\\n
Use a regex to replace it, like this: 使用正则表达式替换它,如下所示:
content = content.replaceAll("Host:\\s*(\\w)*\\.\\w*", "Host: newhost.com")
This will replace anything after Host:
with newHost.com
. 这将用
newHost.com
替换Host:
之后的newHost.com
。
Note: as per comment by cfqueryparam, you may want to usea regex like this to cover .co.uk
and such: 注意:根据cfqueryparam的评论,您可能需要使用这样的正则表达式来覆盖
.co.uk
,例如:
Host:\\s*.*?(?=\\\\r\\\\n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.