简体   繁体   English

正则表达式提取字符串

[英]Regular expression to extract string

I got the following string: 我得到以下字符串:

"url("http://localhost/image/user/temp/n9cec42c939ab461cac7852c267413b1b.jpg")"

How can I extract the file name using a javascript regular expression? 如何使用javascript正则表达式提取文件名?

I tried [^/]+$ but it keeps the ") at the end. 我尝试过[^ /] + $,但最后将“)保留下来。

Thank you. 谢谢。

split on backslash, pop to get the last result, and remove the ") 在反斜杠上分割,弹出以获取最后的结果,然后删除")

'url("http://localhost/image/user/temp/n9cec42c939ab461cac7852c267413b1b.jpg")'.split('/').pop().replace('\")', '')

Example

Or if RegExp is just your thing: 或者,如果RegExp只是您的事:

var url = 'url("http://localhost/image/user/temp/n9cec42c939ab461cac7852c267413b1b.jpg")'; 
url.match(/.+\/(.+)\"\)/)[1]; // file name
[^/]+"\)$

would work on your example. 将适用于您的示例。 If that's not what you're after, please provide more details in your question. 如果这不是您想要的,请在问题中提供更多详细信息。

With a regexp you can use: 使用正则表达式,您可以使用:

'url("http://localhost/image/user/temp/n9cec42c939ab461cac7852c267413b1b.jpg")'.match(/\/([\d\w]+\.[\w]+)/)[1]

assuming your filename consists from az + 0-9 and a three character extension 假设您的文件名由az + 0-9和三个字符扩展名组成

Quite close to what you wrote is 非常接近您写的是

/[^\/]+(?=\"\)$)/

for example 例如

/[^\/]+(?=\"\)$)/.exec(s)

where s is your example string returns the correct filename. 其中s是示例字符串,返回正确的文件名。

(explanation: With regular expressions the form (?=...) means something that must be following the match but that should not be considered part of the match). (说明:对于正则表达式,形式(?=...)表示必须在比赛之后的内容,但不应视为比赛的一部分)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM