Splitting a regex based on spaces but inside brackets [duplicate] - javascript

This question already has answers here:
split a string only on spaces that are outside curly braces
(3 answers)
JavaScript regular expression split by space only in certain context
(3 answers)
Closed 4 years ago.
Problem Faced:
I would like to split a string based on spaces groups, but not if they are inside brackets.
Example :
"abc { def ghi Klm} opqr"
should give me
["abc", "{ def ghi Klm}", "opqr"]
Solution Needed:
What is the most readable and most efficient regex in order to do this ?
I know that splitting around spaces can be done like this :
sentence.split(/s+/)
But I don't know how to go further.
Duplicate Resolution
This question was indeed already solved here (though was in C#). Apologizing

You may use this regex for matching:
/{[^}]*}|\S+/g
RegEx Demo
This regex uses an alternation to match a string between curly brackets using {[^}]*} OR matches 1+ non-whitespace characters using \S+.
Code:
const regex = /{[^}]*}|\S+/gm;
const str = `abc { def ghi Klm} opqr`;
let m = str.match(regex);
console.log(m);

In regex there is a kind of "dualism", that the same task
can be achieved using either splitting on a pattern or
matching on its "negation".
In your case, due to some limitations of Javascript flavour of regex,
the matching variant is better. Use: /{[^}]*}|\S+/g to find
matches in your text.
It containt 2 alternatives:
{[^}]*} - opening bracket, a seuence of chars other than }
and }.
\S+ - a non-empty sequence of chars other than space / tab / newline.
Example code, tested on rextester.com, where just print is used
for test printouts:
var txt = 'abc { def ghi Klm} opqr xxx';
var res = txt.match(/{[^}]*}|\S+/g);
print("Length: " + res.length);
for (var j in res) {
print(res[j]);
}

Related

JavaScript Regex to filter text between two characters [duplicate]

This question already has answers here:
How do I parse a URL into hostname and path in javascript?
(26 answers)
Closed 3 years ago.
I need to filter the text below from the string using Regex JavaScript:
Text: 'http://www.mywebsiteameW1234.com'
Should return only: mywebsitename
So between character dots and only lowercase letters:
My attempt is only returning: mywebsitenameW1234 should remove the numbers:
let text = 'http://www.mywebsitenameW1234.com'
console.log(text.match(/(?<=\.)(.*)(?=\.)/gm)[0])
I tried several ways to try to filter instead of (.*) putting something like ([a-z]+)
but always return null.
What am I doing wrong? Why can't I add those filters in between groups look ahead/behind, etc..?
One expression, for instance, would be:
https?:\/\/(?:www\.)?([a-z]+).*
which is left bounded.
Demo 1
Another one would be,
([a-z]+)[^a-z\r\n]*\.[a-z]{2,6}$
Demo 2
which is right-bounded, and you could also double bound it, if that'd be necessary.
Or with lookarounds, one option would be,
[a-z]+(?=[^a-z\r\n]*\.[a-z]{2,6}$)
Demo 3
const regex = /https?:\/\/(?:www\.)?([a-z]+).*/gm;
const str = `http://www.mywebsiteameW1234.com`;
const subst = `$1`;
const result = str.replace(regex, subst);
console.log(result);
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
RegEx Circuit
jex.im visualizes regular expressions:
How about this one.
The [a-z]* expression ensures that it will only match lowercase letters after the first dot in the string.
let text = 'http://www.mywebsitenameW1234.com'
console.log(text.match(/(?<=\.)[a-z]*/gm)[0])

Javascript Regex replace [] [duplicate]

This question already has answers here:
How can I put [] (square brackets) in RegExp javascript?
(8 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 4 years ago.
I am trying to replace the following in a Regex:-
[company-name]
Using Regex I would expect I could use was to use:-
str.replace(/[company-name]/g, 'Google');
But I know that the regex will replace any matching letter.
How am I able to replace the [company-name] with Google using JS Regex?
Thanks in advance for your help.
But I know that the regex will replace any matching letter.
This is only the case because you have encapsulated your characters in a character class by using [ and ]. In order to treat these as normal characters, you can escape these using \ in front of your special characters:
str.replace(/\[company-name\]/g, 'Google');
See working example below:
const str = "[company-name]",
res = str.replace(/\[company-name\]/g, 'Google');
console.log(res);
You need to escape the starting [ as well, in this case as they are special characters too:
var str = "I am from [company-name]!";
console.log(str.replace(/\[company-name]/gi, "Google"));
str = "[company-name]'s awesome!";
console.log(str.replace(/\[company-name]/gi, "Google"));
you could do it this way :
var txt = "So I'm working at [company-name] and thinking about getting a higher salary."
var pattern = /\[.+\]/g;
console.log(txt.replace(pattern, "Google"))
You should escape special characters like square brackets in this case.
Just use:
str.replace(/\[company-name\]/g, 'Google');

How to match with new RegExp exactly [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 5 years ago.
I have this string:
var str = "https://www.mysite.se/this-match?ba=11"
I need to match it exactly (between / and ?), so only this-match matches, not this-ma or anything (shorter) that is contained in this-match.
I.e:
var myre = new RegExp('\/this-ma\?');
Still matches:
myre.exec(str)[0]
"/this-ma"
How can I avoid that a shorter string contained in this-match does give a match?
The definition of your regex is wrong. You'd think that \? would match literal ? character, instead of being non-greedy modifier. Not true. Quite the opposite, in fact.
var myre = new RegExp('\/this-ma\?');
> /\/this-ma?/
The backslash here works within the string literal, and outputs single ? to regex, which becomes non-greedy modifier. Use the regex literal.
var myre = /\/this-ma\?/

Change particular characters (escape characters) in a string by using regex or indexOf in Javascript [duplicate]

This question already has answers here:
Escaping Strings in JavaScript
(5 answers)
Closed 7 years ago.
I'm trying to change particular characters such as [ ', ", \ ] because I have a problem during INSERT. For example, the string I'm saying "Hi" will be I\'m saying \"Hi\". So basically this method is adding backslash in front of the characters. But I'm not sure how to do this with regex.
I was thinking to do this with IndexOf but the index of the string is changed when I add the backslash to the string.
Any idea how to do this?
This should do exactly what you want:
str = 'I\'m saying "Hi" \\ abc';
str = str.replace(/\\/g, '\\\\').replace(/(['"])/g, '\\$1');
but if you're using SQL, I would really look into prepared statements: https://github.com/felixge/node-mysql#escaping-query-values
You can use $1 the $ means "saved group", and 1 means the first saved group:
So:
string.replace( /(['"\\])/g, "\\$1" )
How this works is:
/ Start RegEx
( Start "saved" or capturing group
['"\\] Matches any of the characters between []
) End "saved" group
/g End RegEx, g means "global" which means it will match multiple times instead of just the first

Matching content within a string with one regex [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Simple way to use variables in regex
(3 answers)
Closed 10 years ago.
I am looking for a way to RegEx match for a string (double quote followed by one or more letter, digit, or space followed by another double quote). For example, if the input was var s = "\"this is a string\"", I would like to create a RegEx to match this string and produce a result of [""this is a string""].
Thank you!
Use the RegExp constructor function.
var s = "this is a string";
var re = new RegExp(s);
Note that you may need to quote the input string.
This should do what you need.
s =~ /"[^"]*"/
The regex matches a double quote, followed by some number of non-quotes, followed by a quote. You'll run into problems if your string has a quote in it, like this:
var s = "\"I love you,\" she said"
Then you'll need something a bit more complicated like this:
s =~ /"([^"]|\\")*"/
I just needed a pattern to match a double quote followed by one or more characters(letters, digits, spaces) followed by another double quote so this did it for me:
/"[^"]*"/

Categories

Resources