正则表达式分裂一个字符串并删除重复出现的字符

时间:2022-08-22 11:54:59

Using python I'm parsing several strings. Sometimes the string has appended several semicolons to it.

使用python我正在解析几个字符串。有时字符串会附加几个分号。

Example strings:

s1="1;Some text"  
s2="2;Some more text;;;;"

The number of appending semicolons varies, but if it's there it's never less than two.
The following pattern matches s1, with s2 it includes the appended semicolons.
How do I redo it to remove those?

附加分号的数量会有所不同,但如果它在那里则不会少于两个。以下模式与s1匹配,s2包含附加的分号。如何重做以删除它们?

pat=re.compile('(?m)^(\d+);(.*)')

2 个解决方案

#1


8  

You can use the str.rstrip([chars])

你可以使用str.rstrip([chars])

This method returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters).

此方法返回字符串的副本,其中所有字符都已从字符串末尾删除(默认空白字符)。

e.g. you can do:

例如你可以做:

s2 = s2.rstrip(";")

You can find more information here.

您可以在这里找到更多信息。

#2


1  

pat = re.compile(r'\d+;[^;]*')

#1


8  

You can use the str.rstrip([chars])

你可以使用str.rstrip([chars])

This method returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters).

此方法返回字符串的副本,其中所有字符都已从字符串末尾删除(默认空白字符)。

e.g. you can do:

例如你可以做:

s2 = s2.rstrip(";")

You can find more information here.

您可以在这里找到更多信息。

#2


1  

pat = re.compile(r'\d+;[^;]*')