Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture group from regex in bash

Tags:

regex

bash

I have the following string /path/to/my-jar-1.0.jar for which I am trying to write a bash regex to pull out my-jar.

Now I believe the following regex would work: ([^\/]*?)-\d but I don't know how to get bash to run it.

The following: echo '/path/to/my-jar-1.0.jar' | grep -Po '([^\/]*?)-\d' captures my-jar-1

like image 332
Cheetah Avatar asked Jun 27 '16 14:06

Cheetah


People also ask

What is regex match group?

Regular expressions allow us to not just match text but also to extract information for further processing. This is done by defining groups of characters and capturing them using the special parentheses ( and ) metacharacters. Any subpattern inside a pair of parentheses will be captured as a group.

What does capture mean in regex?

capturing in regexps means indicating that you're interested not only in matching (which is finding strings of characters that match your regular expression), but you're also interested in using specific parts of the matched string later on.

What is capturing group in regex Javascript?

Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.


1 Answers

In BASH you can do:

s='/path/to/my-jar-1.0.jar'

[[ $s =~ .*/([^/[:digit:]]+)-[[:digit:]] ]] && echo "${BASH_REMATCH[1]}"

my-jar

Here "${BASH_REMATCH[1]}" will print captured group #1 which is expression inside first (...).

like image 88
anubhava Avatar answered Sep 19 '22 10:09

anubhava