i'm using this regex to extract all the numbers from a string.
([\d,]+(?:\.\d+)?)
I'm trying to change it so numbers that are coming after the characters "." "-" "/" won't be return.
I tried
[^-.]([\d,]+(?:\.\d+)?)
or
^[^-.]+$([\d,]+(?:\.\d+)?)
Edit2
Example.
I have this text:
7
.7
-7
/7
-12 123
12,2
22.22
I want the regex to return the the groups 123 12,2 and 22.22
You could use
/(?:^|[^-.\/\d])([\d,]+(?:\.\d+)?)/g
The first part means "start of string or a character which isn't ., / or - (in a non captured group). I added \d in that group to avoid capturing starting from the second digit of a number which shouldn't be captured.
Demonstration (and a way to use it):
var results = [],
regex = /(?:^|[^-.\/\d])([\d,]+(?:\.\d+)?)/g,
text = document.querySelector("p").innerHTML,
m;
while (m=regex.exec(text)) {
results.push(m[1]);
}
document.querySelector("pre").innerHTML=JSON.stringify(results);
<p>123,456 -12 123 some text. 2258 a.666 36,45 a/123 999 22.22</p>
<pre></pre>
Related
I'm working on a Regex.
let phones = ['321-1234567','+355 321 1234567','0103 1234500', '00 355 3211234567' ]
I want to have the following results:
3211234567
+3553211234567
+3551031234500
+3553211234567
I have implemented this:
phones.forEach(phone => {
phone = phone.replace(/^0+/,'+355').replace(/[^+\d]+/g, '')
console.log(phone)
})
Output:
3211234567
+3553211234567
+3551031234500
+3553553211234567 --->wrong , it should be: +3553211234567
and it works only for the three first elements of array, but it doesn't work for the last one (the case when we should replace those two zeros with + ).
So, when the phone number starts with a zero, replace that first zero with +355, when it starts with 00, replace those two zeros with + .
How can I do that using a Regex, or should I use conditions like if phone.startsWith()?
My question is not a duplication of: Format a phone number (get rid of empty spaces and replace the first digit if it's 0)
as the solution there doesn't take in consideration the case when the phone number starts with 00 355 .
let phones = ['321-1234567','+355 321 1234567','0103 1234500', '00 355 3211234567' ]
phones = phones.map(r => r
.replace(/^00/,'+')
.replace(/^0/,'+355')
.replace(/[^+\d]+/g, '')
)
console.log(phones)
You can use
let phones = ['321-1234567','+355 321 1234567','0103 1234500', '00 355 3211234567' ]
for (const phone of phones) {
console.log(
phone.replace(/^0{1,2}/, (x) => x=='00'?'+':'+355')
.replace(/(?!^\+)\D/g, ''))
}
Details:
.replace(/^0{1,2}/, (x) => x=='00'?'+':'+355') - matches 00 or 0 at the start of string, and if the match is 00, replacement is +, else, replacement is +355 (here, x stands for the whole match value and if ? then : else is a ternary operator)
.replace(/(?!^\+)\D/g, '') removes any non-digit if it is not + at the start of string.
Regex details:
^0{1,2} - ^ matches start of string and 0{1,2} matches one or two zero chars
(?!^\+)\D - (?!^\+) is a negative lookahead that fails the match if the char immediately to the right is + that is located at the start of the string (due to ^ anchor), and \D matches any char other than a digit.
your only problem is in this line replace(/^0+/,'+355') replace this with replace(/^0+/,'+')
phones.forEach(phone => {
phone = phone.replace(/^0+/,'+').replace(/[^+\d]+/g, '')
console.log(phone)
})
I need to call minus/hyphen (-) as minus when it comes between one number or any other character.
otherwise, if it comes between characters I need to replace it with an empty string.
For replacing '-' to empty string
readOutText = 'akhila-hegde'
readOutText = readOutText.replace(/([A-Za-z])-([A-Za-z]){0}\w/gi, ' '); // replace '-' with ' '
Now replace '-' with 'minus' in all of the scenarios
9 - {{response}}
9-{{response}}
{{response}}-9
{{response}} - 9
7346788-literallyanything
literallyanything-347583475
I am trying expression in this in this site https://regexr.com/
I have tried a couple of RegEX for 9-{{response}} tyeps.
readOutText = readOutText.replace(/([0-9])[ ]{0,1}-[ ]*\w/gi, ' minus '); // Not working
readOutText = readOutText.replace(/([0-9])[ ]{0,1}-([a-zA-Z0-9!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/? ])\w/gi, ' minus ')
Both of these are matching with 9-{ in the string 9-{{response}}
If I know the above type I can do the same for {{response}}-473 type
Can someone help me with what I have missed?
I made a small example using capture groups to capture the hyphen and classify as minus or true hpyhen. https://regex101.com/r/zb2eZv/1
Capture Group 1 is minus and capture group 2 is hyphen.
(?:\d+(-)\d+)|(?:\w+(-)\w+)
https://jex.im/regulex/#!flags=&re=(%3F%3A%5Cd%2B(-)%5Cd%2B)%7C(%3F%3A%5Cw%2B(-)%5Cw%2B)
It's a litte resource-intensive, and there might be cleverer solutions, but I believe you need a multipass replace.
Replace in case of digit dash digit
Replace in case of digit dash not-digit
Replace in case of not-digit dash digit
This will ignore all non-digit dash non-digit cases.
By the way, [0-9] can be replaced with \d (digit) and [ ]{0,1} can be replaced with * (zero or more spaces).
const inputs = [
"akhila-hegde",
"6 -4",
"9 - {{response}}",
"9-{{response}}",
"{{response}}-9",
"{{response}} - 9",
"7346788-literallyanything",
"literallyanything-347583475",
"7- 8 and some-composed - word then 4-9"
];
const transformMinus = word => word
.replace(/(\d) *- *(\d)/g, "$1 minus $2")
.replace(/(\d) *- *(\D)/g, "$1 minus $2")
.replace(/(\D) *- *(\d)/g, "$1 minus $2")
const outputs = inputs.map(transformMinus);
console.log(outputs);
I have this regex that should match when there's two numbers in brackets
/(P|C\(\d+\,{0,1}\s*\d+\))/g
for example:
C(1, 2) or P(2 3) //expected to match
C(43) or C(43, ) // expect not to match
but it also matches the ones with only 1 number, how can i fix it?
You have a couple of issues. Firstly, your regex will match either P on its own or C followed by numbers in parentheses; you should replace P|C with [PC] (you could use (?:P|C) but [PC] is more performant, see this Q&A). Secondly, since your regex makes both the , and spaces optional, it can match 43 without an additional number (the 4 matches the first \d+ and the 3 the second \d+). You need to force the string to either include a , or at least one space between the numbers. You can do that with this regex:
[PC]\(\d+[ ,]\s*\d+\)
Demo on regex101
Try this regex
[PC]\(\d+(?:,| +) *\d+\)
Click for Demo
Explanation:
[PC]\( - matches either P( or C(
\d+ - matches 1+ digits
(?:,| +) - matches either a , or 1+ spaces
*\d+ - matches 0+ spaces followed by 1+ digits
\) - matches )
You can relax the separator between the numbers by allowing any combination of command and space by using \d[,\s]+\d. Test case:
const regex = /[PC]\(\d+[,\s]+\d+\)/g;
[
'C(1, 2) or P(2 3)',
'C(43) or C(43, )'
].forEach(str => {
let m = str.match(regex);
console.log(str + ' ==> ' + JSON.stringify(m));
});
Output:
C(1, 2) or P(2 3) ==> ["C(1, 2)","P(2 3)"]
C(43) or C(43, ) ==> null
Your regex should require the presence of at least one delimiting character between the numbers.
I suppose you want to get the numbers out of it separately, like in an array of numbers:
let tests = [
"C(1, 2)",
"P(2 3)",
"C(43)",
"C(43, )"
];
for (let test of tests) {
console.log(
test.match(/[PC]\((\d+)[,\s]+(\d+)\)/)?.slice(1)?.map(Number)
);
}
I've being trying to generate a regex for this string:
case1: test-123456789 should get 56789
case2: test-1234-123456789 should get 56789
case3: test-12345 should fail or not giving anything
what I need is a way to get only the last 5 numbers from only 9 numbers
so far I did this:
case.match(/\d{5}$/)
it works for the first 2 cases but not for the last one
You may use
/\b\d{4}(\d{5})$/
See the regex demo. Get Group 1 value.
Details
\b - word boundary (to make sure the digit chunks are 9 digit long) - if your digit chunks at the end of the string can contain more, remove \b
\d{4} - four digits
(\d{5}) - Group 1: five digits
$ - end of string.
JS demo:
var strs = ['test-123456789','test-1234-123456789','test-12345'];
var rx = /\b\d{4}(\d{5})$/;
for (var s of strs) {
var m = s.match(rx);
if (m) {
console.log(s, "=>", m[1]);
} else {
console.log("Fail for ", s);
}
}
You can try this:
var test="test-123456789";
console.log((test.match(/[^\d]\d{4}(\d{5})$/)||{1: null/*default value if not found*/})[1]);
This way supports default value for when not found any matching (look at inserted comment inline above code.).
You can use a positive lookbehind (?<= ) to assert that your group of 5 digits is preceeded by a group of 4 digits without including them in the result.
/(?<=\d{4})\d{5}$/
var inputs = [
"test-123456789", // 56789
"test-1234-123456789", // 56789
"test-12345", //fail or not giving anything
]
var rgx = /(?<=\d{4})\d{5}$/
inputs.forEach(str => {
console.log(rgx.exec(str))
})
I have to match numbers that are having a length between 6-14 separated by space or : or maybe at the start of the line. I'm using the following regex: /[ |:](\d[\s\-()]*){6,14}/g
For the following lines of input it is matching like below,
Number1 :545-867-4845 - match +545-867-4845
Number2=5459485459855 - no match
Number3: 9526 4412 52 - match +9526 4412 52
Number4 55 55 55 - match +55 55 55
Number52017 11 - no match
5459485459855 - no match //should match
Regex is failing the last Use case. What I did wrong?
[ |:] means "Match one space, vertical bar, or colon here." You probably meant (?:^| |:) which means "Match beginning of input, space, or colon here" (the (?:...) is a non-capturing group used to group the alternation, which is what the | is).
There are a couple of other changes I'd make to that, though:
/(?:^|\s|:)(\d[\d\s\-()]{5,13})(?:\s|$)/
Start with beginning-of-input, a space, or a colon
Require a digit
Require 5-13 more digits, spaces, dashes, or parentheses (making a total of 6-14)
Require a space or end-of-input
No g flag
Example and Tests:
var rex = /(?:^|\s|:)(\d[\d\s\-()]{5,13})(?:\s|$)/;
[
{str: "Number1 :545-867-4845", expect: "545-867-4845"},
{str: "Number2=5459485459855", expect: null},
{str: "Number3: 9526 4412 52", expect: "9526 4412 52"},
{str: "Number4 55 55 55", expect: "55 55 55"},
{str: "Number52017 11", expect: null},
{str: "5459485459855", expect: "5459485459855"}
].forEach(test);
function test(entry) {
var match = rex.exec(entry.str);
match = match && match[1];
console.log("Testing " + entry.str + ", got " + match + ", " + (match == entry.expect ? "OK" : "ERROR"));
}
You must add an alternative to match the start of string when matching a space or a colon in front of the expected match: (?:^|[ :]) (or (?:^|[\s:]) to account for any whitespace).
Also, you need to check the context on both sides to ensure you match digit sequences (with some non-digit symbols in between) of the desired length. Right now, you will match 14 digit chunks even in case there are more digits after the 14th digit, and you will also match any trailing non-digit chars you allow in between digits. To only make sure you get 6 to 14 digits, add (?!\d) negative lookahead that will fail the match if there is a digit immediately to the right of the current location.
I suggest re-writing it as
/(?:^|[\s:])(\d(?:[\s()-]*\d){5,13})(?!\d)/g
See the regex demo. Get Group 1 value:
var rx = /(?:^|[ :])(\d(?:[\s()-]*\d){5,13})(?!\d)/g;
var strs = ["Number1 :545-867-4845","Number2=5459485459855","Number3: 9526 4412 52","Number4 55 55 55","Number52017 11","5459485459855"];
for (var s of strs) {
var m;
while (m = rx.exec(s)) {
console.log(s, "=>", m[1]);
}
}