0
def check(text):
    pattern = re.compile(r'\\')
    rv = re.match(pattern, text)
    if rv:
        return True
    else:
        return False

print check('\mi') # True
print check('\ni') # False

Actually,I want text contains '\' is illegal.

But '\n', '\b',etc, python treats them specially,so I can not match them out.

Any solutions?

bin381
  • 342
  • 1
  • 4
  • 14
  • Try **"\\\\\"** as your pattern. I think you might have to escape it once for python, then escape _that_ again for the regex compiler. – byxor Sep 09 '16 at 08:47
  • 3
    First off, `re.match` match the string from beginning you can use `re.search` in order to search through the whole text, secondly you don't need regex for this simple task you can simply check teh membership with `in` operator. – Mazdak Sep 09 '16 at 08:47
  • 1
    If you have `'\ni'` in your source code the string contains no backslash. The string contains a newline followed by an `i`. Don't confuse the **representation** of a string with the content of the string. – Matthias Sep 09 '16 at 08:55
  • If simply checking for a literal '\' is your goal, then a simple `in` operation might do (i.e. `"\\" in text`). – MervS Sep 09 '16 at 09:12
  • 1
    `\ni` **DOES NOT** contain backslash. It contains two characters, newline character and i letter. `\mi` on the other hand, contains backslash. Learn more about [string literals, escape characters, raw strings etc.](https://docs.python.org/2/reference/lexical_analysis.html#string-literals). [`pylint`](https://github.com/PyCQA/pylint) static analysis tool may be helpful, as it yields `anomalous-backslash-in-string` error. – Łukasz Rogalski Sep 09 '16 at 09:22
  • can you clarify if you want to detect ``\`` even in `'\ni'` ? one way is to pass raw string: `check(r'\ni')` – Sundeep Sep 09 '16 at 11:05
  • @spasic we focu on the check function,rather than the input text – bin381 Sep 13 '16 at 08:26
  • @bin381 assuming python 2, try `return '\\' in text.encode('string-escape')` ... see https://stackoverflow.com/questions/2428117/casting-raw-strings-python for details – Sundeep Sep 13 '16 at 08:46

2 Answers2

1

Why would you need or want to use a regex for this?

 return '\\' in text
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Unfortunately, `r'\'` doesn't work like you'd expect. See e.g. https://stackoverflow.com/questions/30283082/why-does-the-single-backslash-raw-string-in-python-cause-a-syntax-error (though there is no good answer). – tripleee Sep 09 '16 at 10:36
0
def check(text):
    rv = re.search('(\\\\)|(\\\n)', string)
    if rv:
        return True
    else:
        return False
string = "\mi"
print check(string) 
string = "\ni"
print check(string) 

Result:

================================ RESTART ===============

True
True

\\\n includes newlines. You can specifically search this way for \n by escaping \\ and adding \n. Works with \b etc...

Roy Holzem
  • 860
  • 13
  • 25