1

I'm having trouble writing a regex that matches these inputs:
1.\\r
2.\\rSomeString
I need a regex that matches \\r

GodSaveTheDucks
  • 756
  • 5
  • 19

3 Answers3

7

Escape the back slashes twice. String's interpret \ as a special character marker.

Use \\\\r instead. \\ is actually interpreted as just \.

EDIT: So as per the comments you want any string that starts with \\r with any string after it. The regex pattern is as follows:

(\\\\r\S*)

\\\\r is the string you want at the start and \S* says any non-white space (\S) can come after any number of times (*).

AER
  • 1,549
  • 19
  • 37
  • https://regex101.com/r/wA9iU7/3 Could you please provide the expression to match more than one time(s) [For `input 2`] – GodSaveTheDucks Aug 31 '16 at 22:26
  • So you'd like to match anything that starts with `\\r`? Or anything with `\\r` anywhere in the string? – AER Aug 31 '16 at 22:32
  • Are you trying to find the first word in a paragraph? – AER Aug 31 '16 at 22:32
  • No, my list contains entries beginning with `\\r` or `\\rWithStrings` or both. Just trying to match pattern and replace them. – GodSaveTheDucks Aug 31 '16 at 22:35
  • Use the pattern above it will match any of it. Do you need code? It works on Python on my machine using `re.sub` – AER Aug 31 '16 at 23:27
1

A literal backslash in Python can be matched with r'\\' (note the use of the raw string literal!). You have two literal backslashes, thus, you need 4 backslashes (in a raw string literal) before r.

Since you may have any characters after \\r, you may use

import re
p = re.compile(r'\\\\r\S*')
test_str = r"\\r \\rtest"
print(p.findall(test_str))

See Python demo

Pattern description:

  • \\\\ - 2 backslashes
  • r - a literal r
  • \S* - zero or more non-whitespace characters.

Variations:

  • If the characters after r can only be alphanumerics or underscore, use \w* instead of \S*
  • If you want to only match \\r before non-word chars, add a \B non-word boundary before the backslashes in the pattern.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • That is how I understand the question and [OP's demo](https://regex101.com/r/wA9iU7/3) where two literal backslashes are used in the input string. I did not post since I did not have any confirmation on what there is in the input. So, judging by that demo, there are 2 literal backslashes. I cannot be too sure, I know. – Wiktor Stribiżew Aug 31 '16 at 23:12
0

You can fine-tune your regular expressions on-line, e.g. at this site.

boardrider
  • 5,882
  • 7
  • 49
  • 86