-3

I have big text file and I have to find all words starts with '$' and ends with ';' like $word;.

import re

text = "$h;BREWERY$h_end;You've built yourself a brewery."
x = re.findall("$..;", text)
print(x)

I want my output like ['$h;', '$h_end;'] How can I do that?

Neloth
  • 27
  • 4

2 Answers2

2

I have to find all words starts with '$' and ends with ';' like $word;.

I would do:

import re
text = "$h;BREWERY$h_end;You've built yourself a brewery."
result = re.findall('\$[^;]+;',text)
print(result)

Output:

['$h;', '$h_end;']

Note that $ needs to be escaped (\$) as it is one of special characters. Then I match 1 or more occurences of anything but ; and finally ;.

Daweo
  • 10,139
  • 2
  • 5
  • 10
1

You may use

\$\w+;

See the regex demo. Details:

  • \$ - a $ char
  • \w+ - 1+ letters, digits, _ (=word) chars
  • ; - a semi-colon.

Python demo:

import re

text = "$h;BREWERY$h_end;You've built yourself a brewery."
x = re.findall(r"\$\w+;", text)
print(x) # => ['$h;', '$h_end;']
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397