Reputation: 19
I was tasked with creating a regex to match the last two characters in a name given a specific string (input):
1732 - George Washinton Junior - US president - 1799
the regex should match the following:
ge, on, or
I managed to create a regex to only match the name:
(?<=\d - ).*(?=- \D)
which returns:
George Washinton Junior
//note the space at the end of string
I apply a second regex on this:
\w{2}(?= )
which matches the desired values: ge, on, or
. I was challenged to come up with a regex that combines both of them together to achieve the same results (on the original input). Since I'm a newbie in regex I have no idea how this could be achieved. I would really appreciate some feedback as to how I should/could approach this task :)
Upvotes: 1
Views: 739
Reputation:
No need to go back, better to go forward.
Its faster and it's compatible with all browsers.
[a-z]{2}(?=\s(?:[^-]*-){2}\s*\d+\s*$)
see https://regex101.com/r/XLTrnb/1
Upvotes: 0
Reputation: 626699
You may use
/(?<=^[^-]*\s-\s[^-]*)\S{2}(?!\S)/g
/(?<=^\d+\s+-\s[^-]*)\S{2}(?!\S)/g
See the regex demo #1 and regex demo #2
Details
(?<=^[^-]*\s-\s[^-]*)
- a positive lookbehind matching a location immediately preceded with
^
- start of string[^-]*
- any 0 or more chars other than -
\s-\s
- a -
enclosed with whitespace chars[^-]*
- any 0 or more chars other than -
\S{2}
- any two non-whitespace chars(?!\S)
- a whitespace or end of string is required immediately to the right of the current location.If you need to make sure the two chars are letters, use
/(?<=^[^-]*\s-\s[^-]*)\p{L}{2}(?!\S)/gu
(Note this regex cannot be tested at regex101.com since it does not support Unicode property classes, though JavaScript RegExp
in current Chrome, Firefox and Node.js and some other ennvironments already support them).
JS demo:
const text = "1732 - George Washinton Junior - US president - 1799";
console.log(text.match(/(?<=^[^-]*\s-\s[^-]*)\p{L}{2}(?!\S)/gu));
Upvotes: 0
Reputation: 1110
i think (?<=\d+ - [\w\s]*?)\w{2}(?= )
will work for you as combination
Upvotes: 1