'Match string from beginning to end of string

import re

text = "A random\string here"
test = re.findall('(?<=A ).+\s', text)

I want to print out everything from the end of "A" (excluding the space) to end of string only.

I would like to get just "random\string"



Solution 1:[1]

I would suggest using a positive look ahead (?=) with the pattern \shere that indicates the white space and the word "here", so in that case, with the look behind for the "A" and the white space after the lookahead you'll have your string without the space.

text = "A random\string here"
test=re.findall('(?<=A ).*(?= \shere)', text)

Solution 2:[2]

If you want something as simple I would suggest using split instead of regex (something like ??test=text.split('A')[1])

If you really want to use regex you can use this kind of website to debug it : https://regex101.com/

Solution 3:[3]

Use

import re
text = "A random\string here"
match = re.search('^A\s+(.+)\s', text)
if match:
    print(match.group(1))
else:
    print(None)

You'll get random\string.

See Python proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  A                        'A'
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    .+                       any character except \n (1 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  \s                       whitespace (\n, \r, \t, \f, and " ")

Solution 4:[4]

The issue with the pattern that you tried is that you consume the \s. What you could do is assert it to the right instead.

Note that \s could also match a newline.

(?<=A ).+(?=\s)

See a regex demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Ryszard Czech
Solution 4 The fourth bird