简体   繁体   English

将char插入字符串以结束数字

[英]Insert char to string to end of number

I have ugly string: 我有丑陋的字符串:

oldstr = "0.100% fDrg: 2%,dgdv: 29% fGd dg 0.2%, Ghh-sf 2.2 dbgh: NONE dfgdf6 gd 3 "

I need to insert char | 需要插入char | after the last digit of number for next splitting by this inserted | 这个插入一次分割号的最后一位数字后| . There is also value none , where is also added this separator: 还有值none ,其中还添加了这个分隔符:

0.100| fdrg: 2|,dgdv: 29| fgd dg 0.2|, ghh-sf 2.2|dbgh: none| dfgdf6|gd 3|

I try this, but no success: 试试这个,但没有成功:

print re.sub(r'(\d+[a-z %^.])', r'\1|', oldstr.lower())

0.|100%| fdrg: 2%|,dgdv: 29%| fgd dg 0.|2%|, ghh-sf 2.|2 |dbgh: none dfgdf6 |gd 3 |

Any help will be appreciated. 任何帮助将不胜感激。

How about: 怎么样:

>>> re.sub(r"([\d\.]+|NONE)%?", r"\1|", oldstr)
'0.100| fDrg: 2|,dgdv: 29| fGd dg 0.2|, Ghh-sf 2.2| dbgh: NONE| dfgdf6| gd 3| '

Here we are capturing one or more occurences of digits and dots or a NONE in a capturing group (followed by an optional % sign) and replacing it with itself and a pipe character. 在这里,我们捕获一个或多个数字和点的出现或捕获组中NONE (后跟可选的%符号),并用自身和管道字符替换它。

Note that @Wiktor's capturing part of the regular expression is much better than in this answer. 请注意, @ Wiktor捕获正则表达式的一部分比在此答案中要好得多。

You can use 您可以使用

(\bnone\b|\d+(?:\.\d+)?)%?

And replace with \\1| 并用\\1|替换 .

Explanation : 说明

  • (\\bnone\\b|\\d+(?:\\.\\d+)?) - Group 1 matching 2 alternatives: (\\bnone\\b|\\d+(?:\\.\\d+)?) - 第1组匹配2个替代方案:
    • \\bnone\\b - whole word none \\bnone\\b - 全文none
    • | - or... - 要么...
    • \\d+(?:\\.\\d+)? - a float value ( \\d+ matches one or more digits, and (?:\\.\\d+)? matches (optionally) a dot followed with one or more digits) - 浮点值( \\d+匹配一个或多个数字,和(?:\\.\\d+)?匹配(可选)一个点后跟一个或多个数字)
  • %? - an optional (since ? means match one or zero times ) % symbol - 一个可选的(因为?表示匹配一次或零次%符号

See regex demo 请参阅正则表达式演示

Python code: Python代码:

import re
p = re.compile(ur'(\bnone\b|\d+(?:\.\d+)?)%?', re.IGNORECASE)
test_str = "0.100% fDrg: 2%,dgdv: 29% fGd dg 0.2%, Ghh-sf 2.2 dbgh: NONE dfgdf6 gd 3 "
subst = "\1|"
result = re.sub(p, subst, test_str)

If you need to trim the values, you will be able to do it after splitting. 如果您需要修剪值,您可以在拆分后执行此操作。 Also, none can be turned lower case before processing the text with re.sub(r'\\b\\none\\b', 'NONE', input) . 此外,在使用re.sub(r'\\b\\none\\b', 'NONE', input)处理文本之前, none可以转为小写。

import re
oldstr = "0.100% fDrg: 2%,dgdv: 29% fGd dg 0.2%, Ghh-sf 2.2 dbgh: NONE dfgdf6 gd 3"

newstring = re.sub(r"([\.\d]+)", r"\1|", oldstr)
print newstring.replace("%","").replace("NONE","NONE|")

output: 输出:

0.100| fDrg: 2|,dgdv: 29| fGd dg 0.2|, Ghh-sf 2.2| dbgh: NONE| dfgdf6| gd 3|

After a little more thinking here is a one-liner: 经过多一点思考后,这是一个单线:

print re.sub(r"([\.\d'NONE']+)%?", r"\1|", oldstr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM