[英]RegEx matching for removing a sequence of variable length in a number
I have a numpy array of integers that look like this X000Y000.我有一个 numpy 整数数组,看起来像这个 X000Y000。 X and Y can be of length 1, 2, or 3 and might contain 0s. X 和 Y 的长度可以是 1、2 或 3,并且可能包含 0。 I want to transform every element in the array to just X. I feel like a regex could be used for this but cannot figure out a good one to use, or how to apply that to a whole array.我想将数组中的每个元素都转换为 X。我觉得可以为此使用正则表达式,但无法找出一个好的使用方法,或者如何将其应用于整个数组。
Example: 14000010000 should become 140.例如:14000010000 应该变成 140。
I assume X
and Y
can't begin with 0
.我假设X
和Y
不能以0
开头。 [1-9]\\d{0,2}
matches a number from 1 to 3 digits that doesn't begin with 0
. [1-9]\\d{0,2}
匹配不以0
开头的 1 到 3 位数字。
So the regexp to extract X
and Y
should be:所以提取X
和Y
则表达式应该是:
^([1-9]\d{0,2})000([1-9]\d{0,2})000$
Then you can use re.sub()
to remove the zeroes between X
and Y
.然后您可以使用re.sub()
删除X
和Y
之间的零。
regex = re.compile(r'^([1-9]\d{0,2})000([1-9]\d{0,2})000$');
i = 14000010000
istr = str(i)
new_i = int(regex.sub(r'\1\2', istr)
You can map this over your numpy array您可以将其映射到您的 numpy 数组上
regex = re.compile(r'^([1-9]\d{0,2})000([1-9]\d{0,2})000$');
new_array = np.fromiter((int(regex.sub(r'\1\2', str(x)) for x in array), array.dtype)
See Most efficient way to map function over numpy array for various ways of mapping a function over a numpy array.有关在 numpy 数组上映射函数的各种方法,请参阅在 numpy 数组上映射函数的最有效方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.