How to get the second part of a hyphenated word using regex?

Member

by dedrick , in category: Third Party Scripts , a month ago

How to get the second part of a hyphenated word using regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , a month ago

@dedrick 

To get the second part of a hyphenated word using regex, you can use the following regular expression pattern:

1
(?<=-)[a-zA-Z]+


This pattern matches any sequence of one or more alphabetic characters that come after a hyphen. Here's how you can use this pattern in Python code:

1
2
3
4
5
6
import re

text = "hello-world"
second_part = re.search(r'(?<=-)[a-zA-Z]+', text).group()

print(second_part)


In this example, the re.search() function searches for the pattern (?<=-)[a-zA-Z]+ in the text "hello-world". The (?<=-) is a positive lookbehind that matches the hyphen, and [a-zA-Z]+ matches one or more alphabetic characters. The group() method then returns the matched string, which in this case is "world".