regex Python -提取正则表达式匹配并一次性替换它?

tez616oj  于 2023-04-22  发布在  Python
关注(0)|答案(1)|浏览(81)

我想从字符串中删除前导白色,但也要提取它。我使用:

m = re.search( r"^(\s*)", text )
leading_space = m.group(1)
text = re.sub( r"^\s*", "", text )

一定有更好的解决办法吧?
在Perl中,我会写:

$text =~ s/^(\s+)//;
$leading_space = $1;

它简洁得多,并且只运行一次正则表达式。
此外,如果正则表达式的编写方式不能保证它总是匹配(例如,将*替换为+),Python代码将失败,导致丑陋的代码,如:

if m:
  leading_space = m.group(1)
else:
  leading_space = ""

我发现我经常用python写难看的代码,因为我不知道聪明的快捷方式。如果你能帮助我,我渴望学习写更优雅的python。
下面是一个完整的测试脚本:

text = """
 Some text
maybe with multiple lines
"""

print( f"Working with <<{text}>>" )

m = re.search( r"^(\s*)", text )
leading_space = m.group(1)
text = re.sub( r"^\s*", "", text )

print( f"Got leading space: <<{leading_space}>>" )
print( f"and text         : <<{text}>>" )

Perl中的一个:

my $text = "
 Some text
maybe with multiple lines
";

print( "Working with <<$text>>\n" );

$text =~ s/^(\s+)//;
$leading_space = $1;

print( "Got leading space: <<$leading_space>>\n" );
print( "and text         : <<$text>>\n" );
nafvub8i

nafvub8i1#

使用拆包:

import re

text = '   fooo  '

space, text = re.search(r'^(\s*)(.*)', text, flags = re.S).groups()
# ...or       re.search(r'^(\s*)([\s\S]*)', text)

print(space, text)  # '   ', 'fooo  '

相关问题