Regular Expression to reformat a US phone number in Javascript
Assuming you want the format “(123) 456-7890“: Here’s a version that allows the optional +1 international code:
Assuming you want the format “(123) 456-7890“: Here’s a version that allows the optional +1 international code:
I’m looking for a general regex construct to match everything in pattern x EXCEPT matches to pattern y. This is hard to explain both completely and concisely…see Material Nonimplication for a formal definition. For example, match any word character (\w) EXCEPT ‘p’. Note I’m subtracting a small set (the letter ‘p’) from a larger set … Read more
When the separator character (/ in your case) between {pattern} and {string} is contained in one of those, it must be escaped with a \. A trick to avoid that is to use a different separator character, e.g. #: PS: If it should do what I think it should do, your pattern is wrong; see … Read more
The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is twice: Expand snippet And, if there are no matches, it returns 0:
Instead of using the /regex\d/g syntax, you can construct a new RegExp object: You can dynamically create regex objects this way. Then you will do:
As was mentioned in the comments it’s easier to do this as a whitelist – replace the characters which aren’t in your safelist. The caret (^) character is the negation of the set […], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word … Read more
These regexes are equivalent (for matching purposes): /^(7|8|9)\d{9}$/ /^[789]\d{9}$/ /^[7-9]\d{9}$/ The explanation: (a|b|c) is a regex “OR” and means “a or b or c”, although the presence of brackets, necessary for the OR, also captures the digit. To be strictly equivalent, you would code (?:7|8|9) to make it a non capturing group. [abc] is a … Read more
How do I make an expression to match absolutely anything (including whitespaces)?Example: Regex: I bought _____ sheep. Matches: I bought sheep. I bought a sheep. I bought five sheep. I tried using (.*), but that doesn’t seem to be working.
The problem is one of delimeters and escaped characters (as others have mentioned). This will work: Note that I added a forward-slash to the beginning and ending of the expression and escapped (with a back-slash) the forward-slashes in the pattern. To take it one step further, this pattern won’t properly extract the year… just the … Read more
You could use lookaround instead if all you want to match is whitespace: