-5

首先,如果 [0-9]* 将出现在 23 个字符之前,我想从字符串中取出 23 个字符,然后将 [0-9]* 作为整个单词包含在内。假设我有一个字符串:

x = I have a car with tha id 6356

I have tried with x[:23]

但它用于取前 23 个字符。这将在以下情况下失败:

x = I have a car with id [0-9]*[\s]
x1 = color id [0-9]* with [0-9]*[\s]
x2 = id [0-9]*[\s] with [0-9]*[\s] has index no:[0-9]*[\s]
x3 = id[\s] with[\s] model[\s] has index no[\s][0-9]*

output of x:  I have a car with id [0
output of x1: color id [0-9]* with [0
output of x2: id [0-9]* with [0-
output of x3: id[\s] with[\s] model[\

预期输出:

x: I have a car with id [0-9]*[\s]
x1: color id [0-9]* with [0-9]*[\s]
x2: color id [0-9]* with [0-9]*[\s]
x3: id[\s] with[\s] model[\s]
4

2 回答 2

1

看看那个子字符串是否在那里。如果是,则position向上移动,直到超过该子字符串:

x = 'color id [0-9]* with [0-9]*[\s]'
substring = '[0-9]*'
position = 23

length = len(substring)
index = x.find(substring, position - length)

if position - length < index < position + length - 1:
    position = index + length

print x[:position]
于 2012-12-21T07:47:29.680 回答
0

这个正则表达式似乎可以解决问题:

^.{23}\d*

这导致:

'这长长的绳子被砍断了。' 结果是 '这个长字符串是 cho '。
'我的电话号码是 061234567891 很酷。' 结果是 '我的电话号码是 061234567891 '。

阅读第一组比赛,你就会得到你的字符串。

m = re.match(r"^.{23}\d*", x)
result = m.group(0)
于 2012-12-21T11:56:28.177 回答