Reputation: 103
I am looking for a solution to find a regular expression which would give me everything that is in between two characters k
and -
.
Example: get 12
from 42k12-b
I tried doing some regex myself but without much of a success as I need it to exclude first and last character. I tried with:
k(.*)\-
But it is including those two characters.
How can I achieve that ?
Upvotes: 1
Views: 233
Reputation: 71
function createRegExp(str, startChar, endChar) {
let regExpText = startChar + '(.*)' + endChar;
let expression = new RegExp(regExpText, 'g');
return expression.exec(str)[1];
}
This function will take 3 arguments. A string, the character from where the search begins and the character where the search ends, both characters not included in the returned result.
The expression capturing group in it's current format (.*)
will be greedy, so given the string 'abcdabcdabcd' and the 'a' and 'd' characters, it will return the bolded part of the string 'abcdabcdabcd' string , but using the lazy quantifier (.*?)
and given the same characters, it will return this bolded part of the string 'abcdabcdabcd'.
The .exec
function returns an array with 2 elements, first one being the full match of the expression, that includes both the two provided characters and the characters between then, while the second array element is only the characters between the two provided characters.
Please be careful when creating this RegExp dynamically like in the above example because some characters will need to be escaped in the RegExp, otherwise they will count as RegExp general tokens.
Upvotes: 1