简体   繁体   English

正则表达式用于捕获“_”和“。”之间的单词。

[英]Regex for capture the word between “_” and “.”

I would like to use a regex to find the word between _ and . 我想使用正则表达式找到_和之间的单词。 in the filename. 在文件名中。

Example: If the filename reads ---- abc_resend.zip 示例:如果文件名为---- abc_resend.zip

I would like my pattern to return "resend" . 我希望我的模式返回"resend"

I tried using the following pattern: "\\_([az]*)\\." 我尝试使用以下模式: "\\_([az]*)\\." Result: _resend . 结果: _resend

Tried the following pattern to exclude: "(?:\\\\_)([az]*)(?:\\\\.) and am still getting the same result: _resend . 尝试使用以下模式排除: "(?:\\\\_)([az]*)(?:\\\\.)并且仍然得到相同的结果: _resend

What am I doing wrong? 我究竟做错了什么? Please help. 请帮忙。

The issue is that you are looking for a regular expression which matches this certain pattern. 问题是您正在寻找与此特定模式匹配的正则表达式。 I am not sure which language you are writing in, but you want to get this result and then use some kind of strip method in order to remove those two characters from the outside. 我不确定你写的是哪种语言,但你想得到这个结果,然后使用某种条带方法从外面删除这两个字符。 You're going to get this result because you're looking for it: the next step is since you always know what you're gonna get, to use a strip method to remove the rest. 你会得到这个结果,因为你正在寻找它:下一步是因为你总是知道你会得到什么,使用条带方法去除其余部分。 If you let me know which language you are using, I can help you track down the specific syntax. 如果您让我知道您使用的是哪种语言,我可以帮助您跟踪具体语法。

. is a special character in RegEx so you need to escape it with a \\ if you want to match a . RegEx中的一个特殊字符,因此如果要匹配a,则需要使用\\来转义它. character. 字符。 Try this: _([az]*)\\. 试试这个: _([az]*)\\.

You can solve your problem using pattern with this regex _(\\w+)\\. 您可以使用此正则表达式_(\\w+)\\.使用模式解决您的问题_(\\w+)\\. :

String str = "abc_resend.zip";
Pattern pattern = Pattern.compile("_(\\w+)\\.");
Matcher matcher = pattern.matcher(str);

while (matcher.find()) {
    System.out.println(matcher.group(1));
}

Output 产量

resend

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

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