Regex for certain character and anything after that - javascript

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);

Related

Is there a regex to remove everything after comma in a string except first letter

I am trying to remove all the characters from the string after comma except the first letter. The string is basically the last name,first name.
For example:
Smith,John
I tried as below but it removes comma and everything after comma.
let str = "Smith,John";
str = str.replace(/\s/g, ""); // to remove all whitespace if there is any at the beginning, in the middle and at the end
str = str.split(',')[0];
Expected output: Smith,J
Thank you!
Or try (,\w).* with replace:
let str = "Smith,John";
str = str.replace(/(,\w).*/, '$1');
console.log(str);
Try this regex out:
\w+,\w
This matches one or more characters before the comma and then matches only 1 character.
Here is the demo: https://regex101.com/r/bKpWt7/1
Note: \w matches any character from [a-zA-Z0-9_].
Taking optional spaces around the comma in to account, and perhaps multiple "names" before the comma:
*([^\s,][^,\n]*?) *, *([^\s,]).*
* Match optional spaces
( Capture group 1
*([^\s,] Match optional spaces and match at least a single char other than a whitespace char or a ,
[^,\n]*? Match any char except a , or a newline non greedy
) Close group 1
*, * Match a comma between optional spaces
([^\s,]) Capture group 2, match a single char other than , or a whitespace char
.* Match the rest of the line
Regex demo
In the replacement using group 1 and group 2 with a comma in between $1,$2
const regex = / *([^\s,][^,\n]*?) *, *([^\s,]).*/;
[
"Smith,John Jack",
"Smith Lastname , Jack John",
"Smith , John",
" ,Jack"
].forEach(s => console.log(s.replace(regex, "$1,$2")));

How to match 2 separate numbers in Javascript

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)
);
}

regex - all numbers that are not after "-", ".", "/"

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>

RegExp: Look up non-formatted phone number with formatted number

If I have an E.164 formatted phone number and I want to look up any users with that phone number, though their number may not be formatted, what would that regex look like?
Example:
Given:
+1234567891
Regex should match any of:
(123) 456 7891
123-456-7891
+1234567891
123.456.7891
1234567891
Any of the above with trailing or leading whitespace.
var str = '+1234567891',
parts = str.match(/\+((\d{3})(\d{3})(\d{4}))/).slice(1),
num = parts.shift(),
rg = new RegExp(
'\\s*(?:\\+?' + [
num,
parts.join('.'),
parts.join('-'),
'\\(' + parts[0] + '\\) ' + parts.slice(1).join(' ')
].join('|') + ')\\s*');
In this case, it will produce
/\s*(?:\+?1234567891|123.456.7891|123-456-7891|\(123\) 456 7891)\s*/
Try:
/\s*(\+)?(\(\d{3}\)|\d{3})([ -.]|)\d{3}(\3)\d{4}\s*/
See the regex101 example
How it works
\s* matches any preceding white space
(\+)? optionally matches +
(\(\d{3}\)|\d{3}) matches (123) or just 123
([ -.]|) matches , -, . or nothing
\d{3} matches 123
(\3) whatever was matches by ( |-|.|)
\d{4} match 1234
\s* matches any following white space
I think the best you can do is normalize both numbers and compare the result. You can, for example, remove everything that is not a number ([^0-9]) and compare only the digits left.
You can use following regex :
^\s?(\(\d{3}\)|\+?\d{3})([\s-.])?\d{3}\2\d{4}\s?$
Demo :https://www.regex101.com/r/jM2fF4/6

Adding a condition to a regex

Given the Javascript below how can I add a condition to the clause? I would like to add a "space" character after a separator only if a space does not already exist. The current code will result in double-spaces if a space character already exists in spacedText.
var separators = ['.', ',', '?', '!'];
for (var i = 0; i < separators.length; i++) {
var rg = new RegExp("\\" + separators[i], "g");
spacedText = spacedText.replace(rg, separators[i] + " ");
}
'. , ? ! .,?!foo'.replace(/([.,?!])(?! )/g, '$1 ');
//-> ". , ? ! . , ? ! foo"
Means replace every occurence of one of .,?! that is not followed by a space with itself and a space afterwards.
I would suggest the following regexp to solve your problem:
"Test!Test! Test.Test 1,2,3,4 test".replace(/([!,.?])(?!\s)/g, "$1 ");
// "Test! Test! Test. Test 1, 2, 3, 4 test"
The regexp matches any character in the character class [!,.?] not followed by a space (?!\s). The parenthesis around the character class means that the matched separator will be contained in the first backreference $1, which is used in the replacement string. See this fiddle for working example.
You could do a replace of all above characters including a space. In that way you will capture any punctuation and it's trailing space and replace both by a single space.
"H1a!. A ?. ".replace(/[.,?! ]+/g, " ")
[.,?! ] is a chararcter class. It will match either ., ,, ?, ! or and + makes it match atleast once (but if possible multiple times).
spacedText = spacedText.replace(/([\.,!\?])([^\s])/g,"$1 ")
This means: replace one of these characters ([\.,!\?]) followed by a non-whitespace character ([^\s]) with the match from first group and a space ("$1 ").
Here is a working code :
var nonSpaced= 'Hello World!Which is your favorite number? 10,20,25,30 or other.answer fast.';
var spaced;
var patt = /\b([!\.,\?])+\b/g;
spaced = nonSpaced.replace(patt, '$1 ');
If you console.log the value of spaced, It will be : Hello World! Which is your favorite number? 10, 20, 25, 30 or other. answer fast. Notice the number of space characters after the ? sign , it is only one, and there is not extra space after last full-stop.

Categories

Resources