简体   繁体   English

如何在正则表达式中添加空格?

[英]How do I add white space in regex?

I have this code: 我有以下代码:

CODE JS: 代码JS:

const phone= /^\(?(\d{3})\)?[-]?(\d{3})[-]?(\d{4})$/;

After running this code has the following form 运行此代码后具有以下形式

(123)132-1312

I want to add white space before the last parentheses as in the example below. 我想在最后一个括号之前添加空格,如下例所示。

(123 )132-1312

Can you please tell me how to accept changes to the code so that white space? 能否请您告诉我如何接受对代码的更改,使空格为空白?

Thanks in advance! 提前致谢!

EDIT: 编辑:

text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "($1)$2-$3");
var testt=$(this).val().match(text);

I added this code to call here as add white space ... 我添加了此代码以在此处调用以添加空格...

这应该可以根据需要工作:

/^\(?\s*(\d{3})\s*\)?[-]?(\d{3})[-]?(\d{4})$/

Depending on wether you always want the whitespace befor the closeing parenthesis or not your could go with: 根据不同的情况,您始终希望空格位于右括号之间,或者不可以:

^\\(?(\\d{3}\\s?)\\)?[-]?(\\d{3})[-]?(\\d{4})$

Background \\s is for whitespaces. 背景\\s用于空格。 the ? ? stands for 0 or 1 occurrance of the previous sign. 代表前一个符号出现0或1。 if you use + it is one or more and * is for 0 or more occurrences of the previous sign. 如果使用+ ,则表示一个或多个,而*表示0个或多个出现的前一个符号。

To test your regex you can always use regexpal 要测试你的正则表达式,你可以随时使用regexpal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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