0

I want to search string a in string b = "sed s/xxx/[/"

Code:

a = "data sed s/xxx/[/"
b = r'\ssed s/xxx/[/\b'
re.findall(b,a)

Output Error

unexpected end of regular expression.
Harshdeep Sokhey
  • 324
  • 5
  • 15
Yasir NL
  • 53
  • 6

2 Answers2

2

The character [ is a regular-expression metacharacter. In order to match it literally, you need to escape it.

r'\ssed s/xxx/\[/'   # backslash-escape it, or
r'\ssed s/xxx/[[]/'  # put it in a character class

The second example also shows what the metacharacter is actually used for. In regular expressions, [abc] matches a single character out of the enumeration (so either a or b or c); this is called a character class.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • The above solution is working fine. how make generic patter to work for any string – Yasir NL Jan 29 '18 at 06:36
  • It's unclear what you mean; are you looking for https://stackoverflow.com/questions/280435/escaping-regex-string-in-python perhaps? – tripleee Jan 29 '18 at 06:49
1

Try

import re

a = "data sed s/xxx/[/"
b = r'\ssed s/xxx/\[/'

print re.findall(b,a)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • There is no need to escape the last slash. Slash doesn't have any special meaning in Python regular expressions (and if it did, you would have to escape all the slashes). – tripleee Jan 29 '18 at 05:57
  • @tripleee; You are right I did not see that. Thanks. – Rakesh Jan 29 '18 at 05:59
  • The above solution is working fine. how make generic patter to work for any string – Yasir NL Jan 29 '18 at 06:36