0
votes

What is the regular expression to get the position of the last separator character before a certain pattern?

For example, I have a string as follows

some value;some other value;some special XYZ value;some more special XYZ value

Here, the separator character is semicolon (";") and the pattern I am looking for is any string that contains "XYZ".

The correct answer is this case is position 28, which is the last occurence of the separator character (";") before an element containing the match pattern ("XYZ").

What would the regular expression look like?

3

3 Answers

1
votes

Use this regular expression

^.*(;).*XYZ.*$

.*(;).*XYZ.* would match greedily i.e. it would match till the last occurance of ; having XYZ followed by it

1
votes
;(?=[^;]*XYZ)

matches a semicolon that's followed by XYZ within the same segment of the string.

Use it once to find the first occurrence. If you use it repeatedly, you'll find the following occurrences, too.

0
votes

You can do it in two steps:

  • extract the largest substring containing the first occurrence of XYZ preceded by a separator
  • in that substring find the position of the last separator

i.e.,

s = "some value;some other value;some special XYZ value;some more special XYZ value"
s1 = re.findall("^.*?;.*?XYZ",s)[0]
len(re.findall("(.*;)",s1)[0]) --> 28