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

Member

by dedrick , in category: Third Party Scripts , 4 months ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 4 months 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".

Related Threads:

How to replace a word with new word in string using regex in java?
How to delete a word in a column using regex?
How to extract part of string using regex?
How to extract part of string in bash using regex
How to remove part of file name using a regex expression?
How to set max limit for each word in the sentence using regex in java?