Srikanth Jeeva
Srikanth Jeeva

Reputation: 3011

Regular expression extract string

I have a string "@{Name; [email protected]}"

I want to write a regular expression that extracts Name and 11112121 from the above string

This is what I tried.

function formatName(text){ 
  var regex = /@\{([^;]+); ([^\}]+)\}/
  return text.replace(
      regex,
      '$1, $2'
  );  
}

The above gives Name, [email protected]. But I want only Name, 11112121

Upvotes: 0

Views: 88

Answers (3)

user3064914
user3064914

Reputation: 959

try this

var regex = /@\{([^;]+); ([^\}]+)(@.*)\}/

$1 => Name

$2=> 11112121

Here is the working example

Upvotes: 3

Andrew
Andrew

Reputation: 5340

Use match instead, like this:

var regex = /@\{([^;]+);\s+([^@]+)/;

var matches = text.match(regex);

alert(matches[1] + ', ' + matches[2]);

http://jsfiddle.net/rooseve/bM2U6/

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336098

If you want to match everything until the @ character, you can use

var regex = /@\{([^;]+); ([^@]+)/

If you need to verify that the string also contains a } after that, you can add that to the end:

var regex = /@\{([^;]+); ([^@]+)[^}]*\}/

Upvotes: 0

Related Questions