2

I have a string which can be like "some string {{key:value}} again some string {{key:value}}{{key:value}} some string" I want to find all the {{key:value}} matching sub strings from the given string. for this what pattern I am trying is like :

string ="fdfd{{dsfdss:dssssasa}} fdsfdsfds"
pattern = re.compile("\\\\[a-z]\w+\:\[a-z]\w+\}}")
abc = re.search( pattern, string)

I tried it using this also

pattern = re.compile("\\\\[a-z]\w+:[a-zA-Z]\w+\}}")
abc = re.search( pattern, string)

But each time it is returning None

Suggested me the best way to accomplish it.

Sajid Ahmad
  • 1,124
  • 4
  • 18
  • 40

2 Answers2

6

Try this simple regex:

({{(\w+):(\w+)}})

It returns the full match and elements:

MATCH 1
1. [4-23] {{dsfdss:dssssasa}}
2. [6-12] dsfdss
3. [13-21] dssssasa

Try it live here

Python code:

import re
string = u'fdfd{{dsfdss:dssssasa}} fdsfdsfds'
pattern = re.compile(ur'({{(\w+):(\w+)}})')
print(re.findall(pattern, string))

Edit: For only the inner part, the regex is {{(\w+:\w+)}}

Cyrbil
  • 6,341
  • 1
  • 24
  • 40
  • 1
    Fun fact: you can remove extra backslashes and use `({{(\w+):(\w+)}})`. Python re module is still a bit smart and unlike Java recognizes the `{` not followed by a digit and closing brace is a literal `{`. And `}` do not have to be escaped. – Wiktor Stribiżew Nov 23 '15 at 12:49
  • Thank you, but why is that possible ? Is it because the regex engine understand that it is not a quantifier ? How ? – Cyrbil Nov 23 '15 at 12:52
  • 1
    Ok, you edit your answer and answered my interrogation :) – Cyrbil Nov 23 '15 at 12:52
  • Hi @Cybril, thanks for your answer. It works also but what i need is a bit different. I need only the text enclosed in {{}}. – Sajid Ahmad Nov 23 '15 at 12:53
  • Not sure what you mean @SajidAhmad ? Just `dsfdss:dssssasa` ? – Cyrbil Nov 23 '15 at 12:54
  • @SajidAhmad: It is even easier then, and your question is a practically a dupe of [*regex in python dealing with curly braces*](http://stackoverflow.com/questions/10643553/regex-in-python-dealing-with-curly-braces): use `{{(.*?)}}` with `re.findall`. – Wiktor Stribiżew Nov 23 '15 at 12:56
  • yes, I need only this key value pair, not other strings. – Sajid Ahmad Nov 23 '15 at 12:56
  • Move the parenthesis a bit ... `{{(\w+:\w+)}}` you could have figure that by yourself... – Cyrbil Nov 23 '15 at 12:58
0

You can use the following regex:

(\{\{([^\:]+)\:([^\}]+)\}\}
Mayur Koshti
  • 1,794
  • 15
  • 20