Link to home
Start Free TrialLog in
Avatar of eyeqube
eyequbeFlag for India

asked on

regex for compliment

Hi,

      I have a string "Matches any character except a newline". Is it possible to match every other part of this string except "a newline". In other words I need to cut "a newline" and take only the first part of it. How is it possible

BRgds,

kNish
Avatar of ozo
ozo
Flag of United States of America image

(.*)a newline
eyeqube,

If you dot character is matching the newline character and you using this in Python make sure you don't have the DOTALL flag in your expression.  The default is the character won't match a newline but that flag can change it.  If I have misunderstood what you asked then let me know.

Let me know if you have any questions or need more information.

b0lsc0tt
Avatar of eyeqube

ASKER

Hi,

     I tried ozo's suggestion. It does not give me the desired result. let me explain my question again in other words.

   I have a string that has extra information. "//abcd-999/beeHive/hexagon/honey/sugar/honey". This string has the last two folder names "/sugar/honey". I need to have only "//abcd-999/beeHive/hexagon/honey" part stored.

BRgds,

kNish
It seems the string in the original question was misinterpreted, it appears that was just an example string and not meant to be interepreted as a . matches \n question.

It depends on your rules for matching "/sugar/honey" but if it is literal:
re.sub("/sugar/honey$", "", subject)

Open in new window

Avatar of pepr
pepr

It depends on what you really want. But such cases can usually be better solved without regular expressions. It depends what exactly should be removed/replaced. You should clarify your intention better.

Try the snippet below to see how the string can be split by '/', the resulting list modified or extracted and then the other list joined again into a string.
s1 = '//abcd-999/beeHive/hexagon/honey/sugar/honey'
print repr(s1)
 
lst = s1.split('/')
print lst
 
s2 = '/'.join(lst)
print repr(s2)
 
# One possible manipulation.
lst2 = lst[0:5] + lst[-1:]
print lst2
 
s3 = '/'.join(lst2)
print repr(s3)

Open in new window

The above prints the output...

'//abcd-999/beeHive/hexagon/honey/sugar/honey'
['', '', 'abcd-999', 'beeHive', 'hexagon', 'honey', 'sugar', 'honey']
'//abcd-999/beeHive/hexagon/honey/sugar/honey'
['', '', 'abcd-999', 'beeHive', 'hexagon', 'honey']
'//abcd-999/beeHive/hexagon/honey'
Well, it was a little joke ;) The lst2 assignment command was to be...

lst2 = lst[:-2]   # i.e. copy the lst form the beginning except the last two elements
ASKER CERTIFIED SOLUTION
Avatar of jdpipe
jdpipe
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial