我对这个程序没有经验,但这应该适用于 javascript,因此也适用于 Regex 的其他功能最少的实现。
\[?\s*(\d+)\s*(?=(?:,\s*\d+)+|\])(?=[^\[]*\]).
\[? # Literal [, zero or 1 times
\s* # Any number (*) of whitespace characters
(\d+) # Any number of digits, one or more (+)
\s* # Any number (*) of whitespace characters
(?= # Positive lookahead, support for possitive lookahead is key to the regex
(?: # Open non-capturing group
,\s*\d+ # Literal ",", any number of whitespace characters,
# digits one or more
) # Close non-capturing group
| # or
\] # Literal "]"
) # Close positive lookahead
(?= # Open another positive lookahead
[^\[]*\] # Any number of characters that are not "[", as long as they're followed by "]".
# This is only a validation check, those characters won't be caught
) # Close positive lookahead
. # Match any character except newline
如果这个程序支持可变长度的书后,你可以使用它,它只添加一个后视以确保数字也以有效字符为前缀。
\[?\s*(?<=\[[,\d ]*)(\d+)\s*(?=(?:,\s*\d+)+|\])(?=[^\[]*\]).
如果您的引文格式是 100% 可靠[1]
的 , [12]
,[13, 14, 21]
等。您可以使用更简单的版本
\[?\s*(\d+)(?=(?:, \d+)|\])(?=[^\[]*\]).
或者,如果您的程序支持可变长度的后视,\[(?<=\[[,\d ]*)(\d+)(?=(?:, \d+)|\])(?=[^\[]*\]).
.
使用这些表达式中的任何一个:您可以更改最后一个字符 ,.
以\]?
查看仍以逗号分隔的引文[1],[15],[22]
。
*
在许多正则表达式的风格中,lookbehinds——如果完全支持的话,必须是一个没有量词的固定长度,并且所有的交替都是相同的宽度。例如,(?<=a|1)
将工作但(?<=a|12)
,(<=a|1+)
或 (<=a+)
将失败。量词也将应用于lookbehind本身(?<=a)+
编辑:感谢 Rawing 的输入。