**input =>**
+15556662255 blabla +23334445567 blabla [email protected] blabla [email protected] blabla

**i want to output =>**
+15556662255
+23334445567
[email protected]
[email protected]

((+和11个字符以及任何电子邮件地址会在选择并列出之后选择所有文本)
我尝试这个;
var numbers = this.state.text1.match(/[+-]?\d+(?:\.\d+)?/g).map(Number)
          console.log("numbers= ",numbers)
          let myresult = this.state.text1.replace('+'+numbers[0], "");

          console.log("str= ",myresult)
            this.setState({
                text1: '+'+myresult,
                text2: numbers,
            })

最佳答案

执行并查看注释。



const str = '+15556662255 blabla +23334445567 blabla [email protected] blabla [email protected] blabla';

// Remove the multi space and then split by space
const parts = str.replace(/\s\s+/g, ' ').trim().split(' ');

console.log(' ------ Parts ------');
console.log(parts);

// Now that we have each part, detect which is a phone and which is an email
const regexEmail = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;

const regexPhone = /^\+[0-9]{11}$/;

console.log('\n ------ Check ------ ');

// Filter the data to only keep emails and phone number
const filtered = parts.filter((x) => {
  if (regexEmail.test(x)) {
    console.log(`${x}, is a email`);

    return true;
  }

  if (regexPhone.test(x)) {
    console.log(`${x}, is a phone number`);

    return true;
  }

  console.log(`${x}, is something invalid`);

  return false;
});


console.log('\n ------ Filtered ------ ');

console.log(filtered);

09-18 10:16