正则表达式查找包含在两个字符之间的字符串,同时排除分隔符 [英] Regular Expression to find a string included between two characters while EXCLUDING the delimiters
问题描述
我需要从一个字符串中提取一组包含在两个分隔符之间的字符,而不返回分隔符本身.
I need to extract from a string a set of characters which are included between two delimiters, without returning the delimiters themselves.
一个简单的例子应该会有所帮助:
A simple example should be helpful:
目标:提取方括号之间的子串,不返回方括号本身.
Target: extract the substring between square brackets, without returning the brackets themselves.
基本字符串:这是一个测试字符串[或多或少]
如果我使用以下 reg.例如
If I use the following reg. ex.
[.*?]
匹配是[或多或少]
.我只需要获得 more or less
(没有括号).
The match is [more or less]
. I need to get only more or less
(without the brackets).
可以吗?
推荐答案
简单易行:
(?<=[)(.*?)(?=])
从技术上讲,这是使用前瞻和后视.请参阅前瞻和后视零宽度断言.该模式包括:
Technically that's using lookaheads and lookbehinds. See Lookahead and Lookbehind Zero-Width Assertions. The pattern consists of:
- 前面有一个 [ 未被捕获(后视);
- 一个非贪婪的捕获组.在第一个停止是非贪婪的];和
- 后跟一个未被捕获的 ](前瞻).
或者,您可以只捕获方括号之间的内容:
Alternatively you can just capture what's between the square brackets:
[(.*?)]
并返回第一个捕获的组而不是整个匹配.
and return the first captured group instead of the entire match.
这篇关于正则表达式查找包含在两个字符之间的字符串,同时排除分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!