带空格的环绕数字的正则表达式

2024-05-23 18:48:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找一个正则表达式来转换字符串,如下所示:

wienerstr256pta 18 graz austria8051 4

分为以下几个部分:

wienerstr 256 pta 18 graz austria 8051 4

所以我只想把空间之间的每个数字集围起来。你知道吗

我知道我可以很容易地找到数字:

/[0-9]+/g

但是如何用相同的内容加上额外的空格来替换这个匹配?你知道吗


Tags: 字符串内容空间数字空格ptaaustriagraz
2条回答

您可以找到非数字/非空白和数字之间的所有位置,或数字和非数字/非空白之间的所有位置,并在其中插入空格:

(?<=[^0-9\s])(?=[0-9])|(?<=[0-9])(?=[^0-9\s])

替换为空格。你知道吗

参见regex demo。你知道吗

细节

  • (?<=[^0-9\s])-匹配紧跟在字符前面的位置,而不是数字和空格。。。你知道吗
  • (?=[0-9])-后面跟一个数字
  • |-或
  • (?<=[0-9])-匹配紧跟在数字和
  • (?=[^0-9\s])-后跟除数字和空格以外的字符。你知道吗

熊猫测试:

>>> from pandas import DataFrame
>>> import pandas as pd
>>> col_list = ['wienerstr256pta 18 graz austria8051 4']
>>> rx = r'(?<=[^0-9\s])(?=[0-9])|(?<=[0-9])(?=[^0-9\s])'
>>> df = pd.DataFrame(col_list, columns=['col'])
>>> df['col'].replace(rx," ", regex=True, inplace=True)
>>> df['col']
0    wienerstr 256 pta 18 graz austria 8051 4
Name: col, dtype: object
echo "wienerstr256pta18graz austria8051 4" \
| sed -r "s/([^0-9])([0-9])/\1 \2/g;s/([0-9])([^0-9])/\1 \2/g;s/  */ /g"

wienerstr 256 pta 18 graz austria 8051 4

将数字对非数字或非数字对数字的每次更改都替换为两者之间的空白。最后将多个空格压缩为一,因为空格也是非数字。你知道吗

将多个空格(可能在输入中)放在一起:

echo "wienerstr256pta18graz   austria8051 4"     | sed -r "s/([^0-9 ])([0-9])/\1 \2/g;s/([0-9])([^0-9 ])/\1 \2/g;"
wienerstr 256 pta 18 graz   austria 8051 4

相关问题 更多 >