Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to Capture rest of the line

Tags:

regex

I have a regex that captures the following expression

XPT 123A

Now I need to add "something" to my regex to capture the remaining string as a group

XPT 123A I AM VERY HAPPY

So XPT would be group 1, 123A group 2, and I AM VERY HAPPY group 3.

Here is my regex (also here http://regexr.com/4mocf):

^([A-Z]{2,4}).((?=\d)[a-zA-Z\d]{0,4})

EDIT: I dont want to name my groups (editing b/c some people thought it was a dup of another question)

like image 424
Walucas Avatar asked Sep 18 '25 22:09

Walucas


1 Answers

Assuming Group 3 is optional, you may use

^([A-Z]{2,4}) (\d[a-zA-Z\d]{0,3})(?: (.*))?$
^([A-Z]{2,4})\s+(\d[a-zA-Z\d]{0,3})(?:\s+(.*))?$

The \s+ matches any 1+ whitespace chars.

See the regex demo.

Details

  • ^ - start of string
  • ([A-Z]{2,4}) - Group 1: two, three or four uppercase ASCII letters
  • \s+ - 1+ whitespaces
  • (\d[a-zA-Z\d]{0,3}) - Group 2: a digit followed with 0 or more alphanumeric chars
  • (?:\s+(.*))? - an optional non-capturing group matching 1 or 0 occurrences of:
    • \s+ - 1+ whitespaces
    • (.*) - Group 3: any 0+ chars other than line break chars as many as possible
  • $ - end of string
like image 112
Wiktor Stribiżew Avatar answered Sep 21 '25 16:09

Wiktor Stribiżew