有没有办法将电话号码标准化为1-222-444-5555(根据北美标准)? RegEx Demo 测试输出 RegEx电路

我想知道是否可以使用正则表达式模式将电话号码标准化为北美标准(1-222-333-4444)。

该字符串只能使用“-”,空格,“(”,“)”和数字。

谢谢:)

已更新:所有可能的输入是:

(123)-456-7890
123-456-7890
1-(123)-456-7890
1-123-456-7890
(123) 456-7890
123 456-7890
1-(123) 456-7890
1-123 456-7890
(123) 456 7890
123 456 7890
1 123 456 7890
1 (123) 456 7890

尝试输入代码:

public String convertPhone(String newPhone) {
    String regex = "^([\\(]{1}[0-9]{3}[\\)]{1}[ |\\-]{0,1}|^[0-9]{3}[\\-| ])?[0-9]{3}(\\-| ){1}[0-9]{4}$";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(newPhone);
    if (matcher.matches()) {
        newPhone = matcher.replaceFirst("1 \\($1\\) $2-$3");
        return newPhone;
    } else {
        return "-1";
    }
}
skiiyxia 回答:有没有办法将电话号码标准化为1-222-444-5555(根据北美标准)? RegEx Demo 测试输出 RegEx电路

为什么不只删除非数字字符,然后根据字符串长度重新格式化原始数字。

 String[] phoneNumbers = {
            "(123)-456-7890","123-456-7890","1-(123)-456-7890","1-123-456-7890","(123) 456-7890","123 456-7890","1-(123) 456-7890","1-123 456-7890","(123) 456 7890","123 456 7890","1 123 456 7890","1 (123) 456 7890"
      };
      for (String phone : phoneNumbers) {
         String ph = phone.replaceAll("[\\(\\)\\- ]","");

         if (ph.length() == 11) {
            ph = ph.substring(1);
         }
         String ac = ph.substring(0,3);
         String exc = ph.substring(3,6);
         String number = ph.substring(6);
         number = String.format("1 (%s) %s-%s",ac,exc,number);
         System.out.println(number);
      }
,

也许,类似的表达,

(?:1[ -])?[(]?(\d{3})[)]?[ -](\d{3})[ -](\d{4})$

可能会掩盖问题中提出的示例,但可能还会出现一些极端情况,例如任何意外的双空格。

RegEx Demo

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){

        final String regex = "(?m)(?:1[ -])?[(]?(\d{3})[)]?[ -](\d{3})[ -](\d{4})$";
        final String string = "(123)-456-7890\n"
             + "123-456-7890\n"
             + "1-(123)-456-7890\n"
             + "1-123-456-7890\n"
             + "(123) 456-7890\n"
             + "123 456-7890\n"
             + "1-(123) 456-7890\n"
             + "1-123 456-7890\n"
             + "(123) 456 7890\n"
             + "123 456 7890\n"
             + "1 123 456 7890\n"
             + "1 (123) 456 7890";
        final String subst = "1-$1-$2-$3";

        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(string);

        final String result = matcher.replaceAll(subst);

        System.out.println(result);


    }
}

输出

1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890

如果您想简化/更新/探索表达式,请在regex101.com的右上角进行解释。如果您有兴趣,可以观看匹配的步骤或在this debugger link中进行修改。调试器演示了a RegEx engine如何逐步使用一些示例输入字符串并执行匹配过程的过程。


RegEx电路

jex.im可视化正则表达式:

enter image description here

,

我认为这可以通过简单地查找数字而忽略国家代码和数字组之间的所有内容来完成。此正则表达式可以处理所有多余的空格或任何非数字字符且数字之间没有空格的所有示例和情况。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>Finance Tracker</title>
    <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
    <section class="wrapper">
        <h1>Transaction Tracker</h1>
        <form class="frm-transactions">
            <fieldset>
                <legend>Add Transaction</legend>
                <div class="frm-group">
                    <input class="frm-control" type="text" name="description" size="30" placeholder="description" />
                </div>
                <div class="frm-group">
                    <select class="frm-control" name="type">
                        <option value="">type</option>
                        <option value="debit">debit</option>
                        <option value="credit">credit</option>
                    </select>
                </div>
                <div class="frm-group">
                    <i class="edit fa fa-dollar"></i>
                    <input class="frm-control" type="number" name="currency" min="0" max="9999" step="0.01" size="4" placeholder="0.00" />
                </div>
                <div class="frm-group">
                    <input class="frm-control" type="submit" value="add" />
                </div>
                <div class="error"></div>
            </fieldset>
        </form>
        <h2>Transactions</h2>
        <table class="transactions">
            <thead>
                <tr>
                    <td colspan="4" class="right">
                        Total debits: <span class="total debits">$0.00</span>
                        Total credits: <span class="total credits">$0.00</span>
                    </td>
                </tr>
                <tr>
                    <th>Description</th>
                    <th>Type</th>
                    <th class="amount">Amount</th>
                    <th class="tools">Tools</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>
    </section>
    <script src="js/main.js"></script>
</body>
</html>

然后您可以使用此模式替换数字。

window.addEventListener('load',function(e) {

    const addTransForm = document.querySelector("form");
    const tableBody = document.querySelector("tbody");
    const removeIcon = `<img  src="img/remove.svg" data-index>`;

    addTransForm.addEventListener("submit",function(e) {
      e.preventDefault();

      const validateItem = validateTrans(e.target);
      if (validateItem.valid) {
        const htmlString = createTrans(validateItem);
        addTrans(htmlString);
      }
    }); 

    function addTrans(htmlString) {
      const makeIndex = tableBody.children.length;
      let makeNodeFromText = document
        .createRange()
        .createContextualFragment(htmlString);

      let row = makeNodeFromText.querySelector("tr");
      let image = row.querySelector("img");
      image.dataset.index = makeIndex;
      tableBody.appendChild(row);
      addListenerToImage(image);
      updateTotalTime()
    }

    function updateTotalTime(){
      console.log("foobar")
    }

    function addListenerToImage(image) {
      image.addEventListener("click",removeTrans);
    }

     function removeTrans(e){
         let trans = tableBody.querySelectorAll("tr");
         const index = e.target.dataset.index;
         const nodeToRemove = trans[index];
         tableBody.removeChild(nodeToRemove);
         trans = tableBody.querySelectorAll("tr");
         trans.forEach((item,index) => {
           console.log((item.querySelector("img").dataset.index = index));
         });
     }


    function createTrans(newTrans) {
      const transElement = 
      `
        <table>
            <tr>
               <td class="description">${newTrans.description}</td>
               <td class="payment-type">${newTrans.type}</td>
               <td class="currency">${newTrans.currency}</td>
               <td class="remove"> ${removeIcon} </td>
            </tr>
        </table>
      `;
      return transElement;
    }

    function validateTrans(theForm) {
      const transItem = {};
      let errorCount = 0;

      if (theForm.elements.description.value.trim() !== "") {
        transItem.description = theForm.elements.description.value;
      }

      if (theForm.elements.type.value.trim() !== "") {
        transItem.type = theForm.elements.type.value;
      }

      if (theForm.elements.currency.value !== 0) {
        transItem.currency = parseFloat(theForm.elements.currency.value).toFixed(2);
      }

      if (errorCount === 0) {
        transItem.valid = true;
        return transItem;
      }
    }


})

本文链接:https://www.f2er.com/3004666.html

大家都在问