简体   繁体   中英

Regular expression extract string

I have a string "@{Name; 11112121@xyz.com}"

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, 11112121@xyz.com . But I want only Name, 11112121

try this

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

$1 => Name

$2=> 11112121

Here is the working example

Use match instead, like this:

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

var matches = text.match(regex);

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

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

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 = /@\{([^;]+); ([^@]+)[^}]*\}/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM