How can I get the first string matching a regex pattern?
How can I get for example the string "Mi pensas al vi"
out of the regex pattern /^Mi pensas (al|pri) vi$/
?
I don’t need to generate a random string, but to get exactly the first string matching the pattern.
For this simple pattern I could use the following function, but I would need a more general one:
/* Return the first string matching the regex pattern */
RegExp.prototype.firstString = function()
{
return this.toString().replace(/^//, '').replace(//$/, '').replace(/((.*?)|.*?)/g, '$1');
}
var regexp = new RegExp($('#input').text());
$('#output').text(regexp.firstString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Input: <span id="input">Mi pensas (al|pri) vi</span></div>
<div>Output: <span id="output"></span></div>
2
Answers
Based on the assumption I hope you are looking for the
al
part to be returned out of the regex you have.Refer the code below :
You can do this with the randexp package