skip to Main Content

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


  1. 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 :

    function getMatch(){
      let regex = /^Mi pensas (al|pri) vi$/;
      let inputString = "Mi pensas al vi";
    
      let match = regex.exec(inputString);
    
      if (match && match.length > 1) {
        let extractedString = match[1];
        return extractedString;
      } else {
        return "Match not found";
      }
    }
    
    console.log(getMatch())
    Login or Signup to reply.
  2. You can do this with the randexp package

    const RandExp = require("randexp")
    const output = new RandExp(/Mi pensas (al|pri) vi/).gen()
    console.log(output // Mi pensas al vi
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search