I have 2 types of strings. One of them has only 1 space and the second one has 3 spaces.
V1: "100 s" => 1 space. Number followed by a letter. Number can be 1..n digits.
V2: "2 W 10 h" => 3 spaces. Each number is followed by a letter. Again numbers can be 2..n digits.
I need to get rid of the spaces following the numbers. So the end results should be this:
V1: "100 s" -> "100s"
V2: "2 W 10 h" -> "2W 10h"
For now, I use JavaScript split function. However I need regex to replace in a more efficient way. Could you help me with that? Thanks.
const getDelayValue = delayString => {
const splitted = delayString.split(/\s+/);
if (splitted) {
if (splitted.length === 2) {
return `${splitted[0]}${splitted[1]}`;
}
return `${splitted[0]}${splitted[1]} ${splitted[2]}${splitted[3]}`;
}
return delayString;
}
Just replace numbers space string with numbers string:
str = `
100 s
2 W 10 h
`
console.log(
str.replace(/(\d+)\s+([a-z]+)/gi, "$1$2")
)
See here for the meaning of $1 in the replacement.
You can use a regex to remove the spaces
const str1 = '100 s';
const str2 = '2 W 10 h';
function removeSpace(str) {
// as # Keith pointed out, you can also use :
// return str.replace(/(\d+) +/g, '$1');
// \d is a shortcut for [0-9]
return str.replace(/([0-9]+) +/g, '$1');
}
console.log(removeSpace(str1));
console.log(removeSpace(str2));
We are matching a number followed by a space. And then replace it by the number only. To create and test your Regexp, you can use the website https://regex101.com/
Related
I have the following string patterns which I need to match as described.
I need only the first char/digit on each of the following examples. Before the '/' and after any space:
12/5 <--match on 1
x23/4.5 match on x
234.5/7 match on 2
2 - 012.3/4 match on 0
regex something like the following is obviously not enough:
\d(?=\d\/))
To make Clear
I'm actauly using the regex with js split so it's some mpping function which takes each one of the strings and split it on the match. So for example 2 - 012.3/4 would be split to [ 2 - 0, 12.3/4] and 12/5 to 1, [2/5] and so on.
See example (with non working regex) here:
https://regex101.com/r/N1RbGp/1
Try a regular expression like this:
(?<=^|\s)[a-zA-Z0-9](?=[^\s]*[/])
Breaking it down:
(?<=^|\s) is a zero-width (non-capturing) positive lookbehind that ensures
that the match will begin only immediately following start-of-text or a
whitespace character.
[a-zA-Z0-9] matches a single letter or digit.
(?=\S*[/]) is a zero-width (non-capturing) positive lookahead that requires
the matched letter or digit to be followed by zero or more non-whitespace characters and a solidus ('/') character.
Here's the code:
const texts = [
'12/5',
'x23/4.5',
'234.5/7',
'2 - 012.3/4',
];
texts.push( texts.join(', ') );
for (const text of texts) {
const rx = /(?<=^|\s)[a-zA-Z0-9](?=\S*[/])/g;
console.log('');
console.group(`text: '${text}'`);
for(let m = rx.exec(text) ; m ; m = rx.exec(text) ) {
console.log(`matched '${m[0]}' at offset ${m.index} in text.`);
}
console.groupEnd();
}
This is the output:
text: '12/5'
matched '1' at offset 0 in text.
text: 'x23/4.5'
matched 'x' at offset 0 in text.
text: '234.5/7'
matched '2' at offset 0 in text.
text: '2 - 012.3/4'
matched '0' at offset 4 in text.
text: '12/5, x23/4.5, 234.5/7, 2 - 012.3/4'
matched '1' at offset 0 in text.
matched 'x' at offset 6 in text.
matched '2' at offset 15 in text.
matched '0' at offset 28 in text.
The first group in this regex matches the character you're asking for:
([^\s])[^\s]*/
You could also just use:
[^\s]+/
And use the first character of the match (or perhaps you need the rest anyway).
If you want to be able to scan the whole document:
/(?<=(^|\s))\S(?=\S*\/)/g
https://regex101.com/r/rN08sP/1
s = `12/5
x23/4.5
234.5/2
534/5.6
- 49.55/6.5
234.5/7`;
console.log(s.match(/(?<=(^|\s))\S(?=\S*\/)/g));
But if you want to extract that character in a short string: (did you mean there is a space in front?)
It'd be /\s(\S)\S*\//
const arr = [
" 12/5",
" x23/4.5",
" 234.5/7",
" 2 - 012.3/4"
];
arr.forEach(s => {
let result = s.match(/\s(\S)\S*\//);
if (result)
console.log("For", s, "result: ", result[1])
});
But if "beginning of line" is ok... so no space is needed in front, then /(^|\s)(\S)\S*\//:
const arr = [
"12/5",
"x23/4.5",
"234.5/7",
"2 - 012.3/4"
];
arr.forEach(s => {
let result = s.match(/(^|\s)(\S)\S*\//);
if (result)
console.log("For", s, "result: ", result[2])
});
But actually, if you don't mean literally a space but just boundary in general:
const arr = [
"12/5",
"x23/4.5",
"234.5/7",
"2 - 012.3/4"
];
arr.forEach(s => {
let result = s.match(/\b(\S)\S*\//);
if (result)
console.log("For", s, "result: ", result[1])
});
I am trying to write a regular expression which returns a string which is between parentheses. For example: I want to get the string which resides between the strings "(" and ")"
I expect five hundred dollars ($500).
would return
$500
Found Regular expression to get a string between two strings in Javascript
I don't know how to use '(', ')' in regexp.
You need to create a set of escaped (with \) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group:
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec("I expect five hundred dollars ($500).");
//matches[1] contains the value between the parentheses
console.log(matches[1]);
Breakdown:
\( : match an opening parentheses
( : begin capturing group
[^)]+: match one or more non ) characters
) : end capturing group
\) : match closing parentheses
Here is a visual explanation on RegExplained
Try string manipulation:
var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var newTxt = txt.split('(');
for (var i = 1; i < newTxt.length; i++) {
console.log(newTxt[i].split(')')[0]);
}
or regex (which is somewhat slow compare to the above)
var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var regExp = /\(([^)]+)\)/g;
var matches = txt.match(regExp);
for (var i = 0; i < matches.length; i++) {
var str = matches[i];
console.log(str.substring(1, str.length - 1));
}
Simple solution
Notice: this solution can be used for strings having only single "(" and ")" like string in this question.
("I expect five hundred dollars ($500).").match(/\((.*)\)/).pop();
Online demo (jsfiddle)
To match a substring inside parentheses excluding any inner parentheses you may use
\(([^()]*)\)
pattern. See the regex demo.
In JavaScript, use it like
var rx = /\(([^()]*)\)/g;
Pattern details
\( - a ( char
([^()]*) - Capturing group 1: a negated character class matching any 0 or more chars other than ( and )
\) - a ) char.
To get the whole match, grab Group 0 value, if you need the text inside parentheses, grab Group 1 value.
Most up-to-date JavaScript code demo (using matchAll):
const strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
const rx = /\(([^()]*)\)/g;
strs.forEach(x => {
const matches = [...x.matchAll(rx)];
console.log( Array.from(matches, m => m[0]) ); // All full match values
console.log( Array.from(matches, m => m[1]) ); // All Group 1 values
});
Legacy JavaScript code demo (ES5 compliant):
var strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
var rx = /\(([^()]*)\)/g;
for (var i=0;i<strs.length;i++) {
console.log(strs[i]);
// Grab Group 1 values:
var res=[], m;
while(m=rx.exec(strs[i])) {
res.push(m[1]);
}
console.log("Group 1: ", res);
// Grab whole values
console.log("Whole matches: ", strs[i].match(rx));
}
Ported Mr_Green's answer to a functional programming style to avoid use of temporary global variables.
var matches = string2.split('[')
.filter(function(v){ return v.indexOf(']') > -1})
.map( function(value) {
return value.split(']')[0]
})
Alternative:
var str = "I expect five hundred dollars ($500) ($1).";
str.match(/\(.*?\)/g).map(x => x.replace(/[()]/g, ""));
→ (2) ["$500", "$1"]
It is possible to replace brackets with square or curly brackets if you need
For just digits after a currency sign : \(.+\s*\d+\s*\) should work
Or \(.+\) for anything inside brackets
let str = "Before brackets (Inside brackets) After brackets".replace(/.*\(|\).*/g, '');
console.log(str) // Inside brackets
var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/;
alert(rex.exec(str));
Will match the first number starting with a $ and followed by ')'. ')' will not be part of the match. The code alerts with the first match.
var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/g;
var matches = str.match(rex);
for (var i = 0; i < matches.length; i++)
{
alert(matches[i]);
}
This code alerts with all the matches.
References:
search for "?=n"
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
search for "x(?=y)"
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Simple:
(?<value>(?<=\().*(?=\)))
I hope I've helped.
I have problem with simple rexex. I have example strings like:
Something1\sth2\n649 sth\n670 sth x
Sth1\n\something2\n42 036 sth\n42 896 sth y
I want to extract these numbers from strings. So From first example I need two groups: 649 and 670. From second example: 42 036 and 42 896. Then I will remove space.
Currently I have something like this:
\d+ ?\d+
But it is not a good solution.
You can use
\n\d+(?: \d+)?
\n - Match new line
\d+ - Match digit from 0 to 9 one or more time
(?: \d+)? - Match space followed by digit one or more time. ( ? makes it optional )
let strs = ["Something1\sth2\n649 sth\n670 sth x","Sth1\n\something2\n42 036 sth\n42 896 sth y"]
let extractNumbers = str => {
return str.match(/\n\d+(?: \d+)?/g).map(m => m.replace(/\s+/g,''))
}
strs.forEach(str=> console.log(extractNumbers(str)))
If you need to remove the spaces. Then the easiest way for you to do this would be to remove the spaces and then scrape the numbers using 2 different regex.
str.replace(/\s+/, '').match(/\\n(\d+)/g)
First you remove spaces using the \s token with a + quantifier using replace.
Then you capture the numbers using \\n(\d+).
The first part of the regex helps us make sure we are not capturing numbers that are not following a new line, using \ to escape the \ from \n.
The second part (\d+) is the actual match group.
var str1 = "Something1\sth2\n649 sth\n670 sth x";
var str2 = "Sth1\n\something2\n42 036 sth\n42 896 sth y";
var reg = /(?<=\n)(\d+)(?: (\d+))?/g;
var d;
while(d = reg.exec(str1)){
console.log(d[2] ? d[1]+d[2] : d[1]);
}
console.log("****************************");
while(d = reg.exec(str2)){
console.log(d[2] ? d[1]+d[2] : d[1]);
}
replacing the first and last few characters with the * character, i am able to solve the str1 case. How can i solve the remaining one. Right now i am able to mask the last 4 characters.
how can i mask the first 3 or 4 characters. ? whats wrong in the regex pattern
var str1 = "1234567890123456";
str1 = str1.replace(/\d(?=\d{4})/g, "*");
console.log(str1)
var str2 = "123-456-789-101112"
str2 = str2.replace(/\d(?=\d{4})/g, "*");
console.log(str2) // expected ***-***-***-**1112
var str3 = "abc:def:12324-12356"
str3 = str3.replace(/\d(?=\d{4})/g, "*");
console.log(str3) // expected ***:***:*****-*2356
Right now it is masking only the four characters from last, how can i mask 4 characters from front also like
1234567890123456 => 1234********3456
123-456-789-101112 => 123-4**-***-**1112
abc:def:12324-12356 => abc:d**:*****-*2356
One option is to lookahead for non-space characters followed by 4 digits. Since you want to replace the alphabetical characters too, use a character set [a-z\d] rather than just \d:
const repl = str => console.log(str.replace(/[a-z\d](?=\S*\d{4})/g, "*"));
repl("1234567890123456");
repl("123-456-789-101112");
repl("abc:def:12324-12356");
If you want to keep the first 4 alphanumeric characters as well, then it's significantly more complicated - match and capture the first 4 characters, possibly interspersed with separators, then capture the in-between characters, then capture the last 4 digits. Use a replacer function to replace all non-separator characters in the second group with *s:
const repl = str => console.log(str.replace(
/((?:[a-z\d][-#.:]?){4})([-#:.a-z\d]+)((?:[a-z\d][-#.:]?){4})/ig,
(_, g1, g2, g3) => g1 + g2.replace(/[a-z\d]/ig, '*') + g3
));
repl("1234567890123456");
repl("123-456-789-101112");
repl("abc:def:12324-12356");
repl("test#test.com");
I am trying to write a regular expression which returns a string which is between parentheses. For example: I want to get the string which resides between the strings "(" and ")"
I expect five hundred dollars ($500).
would return
$500
Found Regular expression to get a string between two strings in Javascript
I don't know how to use '(', ')' in regexp.
You need to create a set of escaped (with \) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group:
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec("I expect five hundred dollars ($500).");
//matches[1] contains the value between the parentheses
console.log(matches[1]);
Breakdown:
\( : match an opening parentheses
( : begin capturing group
[^)]+: match one or more non ) characters
) : end capturing group
\) : match closing parentheses
Here is a visual explanation on RegExplained
Try string manipulation:
var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var newTxt = txt.split('(');
for (var i = 1; i < newTxt.length; i++) {
console.log(newTxt[i].split(')')[0]);
}
or regex (which is somewhat slow compare to the above)
var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var regExp = /\(([^)]+)\)/g;
var matches = txt.match(regExp);
for (var i = 0; i < matches.length; i++) {
var str = matches[i];
console.log(str.substring(1, str.length - 1));
}
Simple solution
Notice: this solution can be used for strings having only single "(" and ")" like string in this question.
("I expect five hundred dollars ($500).").match(/\((.*)\)/).pop();
Online demo (jsfiddle)
To match a substring inside parentheses excluding any inner parentheses you may use
\(([^()]*)\)
pattern. See the regex demo.
In JavaScript, use it like
var rx = /\(([^()]*)\)/g;
Pattern details
\( - a ( char
([^()]*) - Capturing group 1: a negated character class matching any 0 or more chars other than ( and )
\) - a ) char.
To get the whole match, grab Group 0 value, if you need the text inside parentheses, grab Group 1 value.
Most up-to-date JavaScript code demo (using matchAll):
const strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
const rx = /\(([^()]*)\)/g;
strs.forEach(x => {
const matches = [...x.matchAll(rx)];
console.log( Array.from(matches, m => m[0]) ); // All full match values
console.log( Array.from(matches, m => m[1]) ); // All Group 1 values
});
Legacy JavaScript code demo (ES5 compliant):
var strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
var rx = /\(([^()]*)\)/g;
for (var i=0;i<strs.length;i++) {
console.log(strs[i]);
// Grab Group 1 values:
var res=[], m;
while(m=rx.exec(strs[i])) {
res.push(m[1]);
}
console.log("Group 1: ", res);
// Grab whole values
console.log("Whole matches: ", strs[i].match(rx));
}
Ported Mr_Green's answer to a functional programming style to avoid use of temporary global variables.
var matches = string2.split('[')
.filter(function(v){ return v.indexOf(']') > -1})
.map( function(value) {
return value.split(']')[0]
})
Alternative:
var str = "I expect five hundred dollars ($500) ($1).";
str.match(/\(.*?\)/g).map(x => x.replace(/[()]/g, ""));
→ (2) ["$500", "$1"]
It is possible to replace brackets with square or curly brackets if you need
For just digits after a currency sign : \(.+\s*\d+\s*\) should work
Or \(.+\) for anything inside brackets
let str = "Before brackets (Inside brackets) After brackets".replace(/.*\(|\).*/g, '');
console.log(str) // Inside brackets
var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/;
alert(rex.exec(str));
Will match the first number starting with a $ and followed by ')'. ')' will not be part of the match. The code alerts with the first match.
var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/g;
var matches = str.match(rex);
for (var i = 0; i < matches.length; i++)
{
alert(matches[i]);
}
This code alerts with all the matches.
References:
search for "?=n"
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
search for "x(?=y)"
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Simple:
(?<value>(?<=\().*(?=\)))
I hope I've helped.