[英]How to match filename words without the extension using regex?
I want to match the words in a filename without characters like underscores (_) and the file extension.我想匹配文件名中不带下划线 (_) 和文件扩展名等字符的单词。 For example, if i have the files image_one.jpg and image_two.png then how can I match only
image one
and image two
?例如,如果我有文件 image_one.jpg 和 image_two.png 那么我如何才能只匹配
image one
和image two
? I am not sure how to exclude the underscore and the.extension.我不确定如何排除下划线和.extension。
So far, I have \w*_\w*
but it matches the file name including the underscore ie image_one
and image_two
到目前为止,我有
\w*_\w*
但它与包含下划线的文件名匹配,即image_one
和image_two
Your pattern \w*_\w*
could possibly also match a single _
as the word chars are optional.您的模式
\w*_\w*
也可能匹配单个_
因为单词字符是可选的。
As \w
also matches an underscore, you can exclude it from \w
by using a negated character class.由于
\w
也匹配下划线,因此您可以使用否定字符 class 将其从\w
中排除。 [^\W_]
. [^\W_]
。
To get both values, you could use 2 capturing groups and if the pattern must only match at the end of the string you can add $
at the end.要获取这两个值,您可以使用 2 个捕获组,如果模式只能在字符串末尾匹配,您可以在末尾添加
$
。
([^\W_]+)_([^\W_]+)\.\w+
Explanation解释
([^\W_]+)
Capture group 1, match 1+ times a word char except _
([^\W_]+)
捕获组 1,匹配 1+ 次除_
之外的单词字符_
Match the underscore _
匹配下划线([^\W_]+)
Capture group 2, same as for group 1 ([^\W_]+)
捕获组 2,与组 1 相同\.\w+
Match a .
\.\w+
匹配一个.
and 1+ word chars (or \.(?:jpg|png)
to be more precise)\.(?:jpg|png)
更准确) See a Regex demo查看正则表达式演示
const regex = /([^\W_]+)_([^\W_]+)\.\w+/; [ "image_one.jpg", "image_two.png" ].forEach(s => console.log(s.match(regex).slice(1)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.