gpt4 book ai didi

正则表达式捕获分隔符之间的字符串

转载 作者:行者123 更新时间:2023-12-05 00:31:19 25 4
gpt4 key购买 nike

this问题提供了用于捕获分隔符之间的字符串的正则表达式:

测试: This is a test string [more or less]
正则表达式: (?<=\[)(.*?)(?=\])
返回: more or less
如果要捕获的字符串也包含分隔符怎么办?

测试 1: This is a test string [more [or] less]
返回 1: more [or] less
测试 2: This is a test string [more [or [and] or] less]
返回 2: more [or [and] or] less
和多个括号?

测试 3: This is a test string [more [or [and] or] less] and [less [or [and] or] more]
返回3: more [or [and] or] less , less [or [and] or] more
哪个正则表达式会这样做?或者哪个小 ruby​​/python 脚本可以做到这一点?

最佳答案

在 JavaScript 中

var str = 'This is a test string [more [or [and] or] less]';    
str = str.match( /\[(.+)\]/ )[1];
// "more [or [and] or] less"

如果省略 ? , .+会贪婪地匹配到最后一个 ] .

在 python 中
str = "This is a test string [more [or [and] or] less]"
re.search( "(?<=\[).+(?=\])", str ).group()
// "more [or [and] or] less"

更新 对于多个嵌套括号

在 JavaScript 中
var matches = [],
str = 'This is a test string [more [or [and] or] less] and [less [or [and] or] more] and [more]';

str.replace( /\[([^\]]*\[?[^\]]*\]?[^[]*)\]/g, function ( $0, $1 ) {
$1 && matches.push( $1 );
});

console.log( matches );
// [ "more [or [and] or] less", "less [or [and] or] more", "more" ]

在 python 中
import re
str = 'This is a test string [more [or [and] or] less] and [less [or [and] or] more] and [more]'

matches = re.findall( r'\[([^\]]*\[?[^\]]*\]?[^[]*)\]', str )

print matches
# [ 'more [or [and] or] less', 'less [or [and] or] more', 'more' ]

关于正则表达式捕获分隔符之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15031253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com