regex - python 用奇怪的字符替换行文本

标签 regex python-3.x line str-replace

如何使用 python 替换以下内容

GSA*HC*11177*NYSfH-EfC*23130303*0313*1*R*033330103298
STEM*333*3001*0030303238
BHAT*3319*33*33377*23330706*031829*RTRCP
NUM4*41*2*My Break Room Place*****6*1133337

我想替换第一次出现 '*' 后的所有字符。除 '*' 之外的所有字符都必须替换

输入示例:

NUM4*41*2*My Break Room Place*****6*1133337

示例输出:

NUM4*11*1*11 11111 1111 11111*****1*1111111

最佳答案

相当简单,使用回调返回组 1(如果匹配)不变,否则
返回替换 1

注意 - 这也适用于多行字符串。
如果您需要,只需将 (?m) 添加到正则表达式的开头即可。 (?m)(?:(^[^*]*\*)|[^*\s])

您可能希望首先测试字符串中的 * 字符。

    ( ^ [^*]* \* )           # (1), BOS/BOL up to first *
 |                         # or,
    [^*\s]                   # Not a * nor whitespace

Python

import re

def repl(m):
    if ( m.group(1) ) : return m.group(1)
    return "1"

str = 'NUM4*41*2*My Break Room Place*****6*1133337'

if ( str.find('*') ) :
    newstr = re.sub(r'(^[^*]*\*)|[^*\s]', repl, str)
    print newstr
else :
    print '* not found in string'

输出

NUM4*11*1*11 11111 1111 11111*****1*1111111

关于regex - python 用奇怪的字符替换行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45172969/

相关文章:

reporting-services - SSRS 报告未显示线条

regex - 使用groovy RegEx来获取属性值:grails消息标签中的代码

regex - 围绕外部定界符拆分字符串,尊重字符组

PHP - 在文件中查找一个字符串然后显示它的行号

python - 模块未找到错误: No module named 'tensorflow' ?

python - Linux中的Python和python3有不同的pip吗?

python - 用于在 Python 中将长字符串写入文件的干净代码

c++ - tr1::regex 正则表达式在嵌套大括号上抛出异常

regex - 正则表达式仅匹配小写字母

python - 如何让脚本等待用户在 Tkinter 中交互?