In the past, I had this regex:
\{(.*?)\}
And entered this string:
logs/{thing:hi}/{thing:hello}
Then I used the following:
console.log(string.split(regex).filter((_, i) => i % 2 === 1));
To get this result:
thing:hi
thing:hello
For irrelevant design reasons, I changed my regex to:
\{.*?\}
But now, when using the same test string and split command, it returns only this:
/
I want it to return this:
{thing:hi}
{thing:hello}
How can I modify the split (or anything else) to do this?
Why not use match?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
The match() method retrieves the matches when matching a string against a regular expression.
If you're only interested in returning the two string matches then it's much simpler than using split.
var foo = "logs/{thing:hi}/{thing:hello}";
console.log(foo.match(/{.*?}/g));
Related
How to get all text following the symbol ":"?
I have tried:
'prop:bool*'.match(/:(.[a-z0-9]+)/ig)
But it returns [":bool"] not ["bool"].
Update:
I need to use this inside the following expression:
'prop:bool*'.match(/^[a-z0-9]+|:.[a-z0-9]+|\*/ig);
So that the result becomes:
["prop", "bool", "*"]
You could solve this by performing a positive lookbehind action.
'prop:bool*'.match(/^[a-z0-9]+|(?<=:).[a-z0-9]+|\*/ig)
The positive lookbehind is the (?<=:) part of the regex and will here state a rule of must follow ':'.
The result should here be ["prop", "bool", "*"].
Edit:
Original requirements were somewhat modified by original poster to return three groups of answers. My original code, returning one answer, was the following:
'prop:bool*'.match(/(?<=:).[a-z0-9]+/ig)
This is not a pure regex solution since it takes advantage of the String Object with its substring() method, as follows:
var str = 'prop:bool*';
var match = str.match(/:(.[a-z0-9]+)/ig).pop().substring(1,str.length);
console.log(match);
When the match is successful, an array of one element will hold the value :bool. That result just needs to have the bool portion extracted. So, the element uses its pop() method to return the string value. The string in turn uses its substring() method to bypass the ':' and to extract the desired portion, namely bool.
var [a,b,c] = 'prop:bool*'.match(/^([a-z0-9]+)|:(.[a-z0-9]+)|(\*)/ig);
console.log(a,b.substring(1,b.length),c);
To return three groups of data, the code uses capture groups and trims off the colon by using the substring() method of b.
You could simply do:
'prop:bool*'.match(/:(.[a-z0-9]+)/)[1]
If your entire string is of the form you show, you could just use a regex with capture groups to get each piece:
console.log('prop:bool*'.match(/^([a-z0-9]+):(.[a-z0-9]+)(\*)/i).slice(1));
Here is my string:
Organization 2
info#something.org.au more#something.com market#gmail.com single#noidea.com
Organization 3
headmistress#money.com head#skull.com
Also this is my pattern:
/^.*?#[^ ]+|^.*$/gm
As you see in the demo, the pattern matches this:
Organization 2
info#something.org.au
Organization 3
headmistress#money.com
My question: How can I make it inverse? I mean I want to match this:
more#something.com market#gmail.com single#noidea.com
head#skull.com
How can I do that? Actually I can write a new (and completely different) pattern to grab expected result, but I want to know, Is "inverting the result of a pattern" possible?
No, I don't believe there is a way to directly inverse a Regular Expression but keeping it the same otherwise.
However, you could achieve something close to what you're after by using your existing RegExp to replace its matches with an empty string:
var everythingThatDidntMatchStr = str.replace(/^.*?#[^ ]+|^.*$/gm, '');
You can replace the matches from first RegExp by using Array.prototype.forEach() to replace matched RegExp with empty string using `String.ptototype.replace();
var re = str.match(/^.*?#[^ ]+|^.*$/gm);
var res = str;
re.forEach(val => res = res.replace(new RegExp(val), ""));
I'm getting nowhere with this...
I need to test a string if it contains %2 and at the same time does not contain /. I can't get it to work using regex. Here is what I have:
var re = new RegExp(/.([^\/]|(%2))*/g);
var s = "somePotentially%2encodedStringwhichMayContain/slashes";
console.log(re.test(s)) // true
Question:
How can I write a regex that checks a string if it contains %2 while not containing any / slashes?
While the link referred to by Sebastian S. is correct, there's an easier way to do this as you only need to check if a single character is not in the string.
/^[^\/]*%2[^\/]*$/
EDIT: Too late... Oh well :P
Try the following:
^(?!.*/).*%2
either use inverse matching as shown here: Regular expression to match a line that doesn't contain a word?
or use indexOf(char) in an if statement. indexOf returns the position of a string or char in a string. If not found, it will return -1:
var s = "test/";
if(s.indexOf("/")!=-1){
//contains "/"
}else {
//doesn't contain "/"
}
I am clueless about regular expressions, but I know that they're the right tool for what I'm trying to do here: I'm trying to extract a numerical value from a string like this one:
approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^
Ideally, I'd extract the following from it: 12345678901234567890123456789012 None of the regexes I've tried have worked. How can I get the value I want from this string?
This will get all the numbers:
var myValue = /\d+/.exec(myString)
mystr.match(/assignment_group=([^\^]+)/)[1]; //=> "12345678901234567890123456789012"
This will find everything from the end of "assignment_group=" up to the next caret ^ symbol.
Try something like this:
/\^assignment_group=(\d*)\^/
This will get the number for assignment_group.
var str = 'approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^',
regex = /\^assignment_group=(\d*)\^/,
matches = str.match(regex),
id = matches !== null ? matches[1] : '';
console.log(id);
If there is no chance of there being numbers anywhere but when you need them, you could just do:
\d+
the \d matches digits, and the + says "match any number of whatever this follows"
What is the JavaScript equivalent of this .NET code?
var b = Regex.IsMatch(txt, pattern);
Here are the useful functions for working with regexes.
exec A RegExp method that executes a search for a match in a string. It returns an array of information.
test A RegExp method that tests for a match in a string. It returns true or false.
match A String method that executes a search for a match in a string. It returns an array of information or null on a mismatch.
search A String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails.
replace A String method that executes a search for a match in a string, and replaces the matched substring with a replacement substring.
split A String method that uses a regular expression or a fixed string to break a string into an array of substrings.
Source: MDC
So to answer your question, as the others have said:
/pattern/.test(txt)
Or, if it is more convenient for your particular use, this is equivalent:
txt.search(/pattern/) !== -1
var b = /pattern/.test(txt);
/pattern/.test(txt);
E.g.:
/foo \w+/.test("foo bar");
It returns true for a match, just like IsMatch.
var regex = new RegExp(pattern);
var b = regex.test(text);
You can also use var b = /pattern/.test(text) but then you can't use a variable for the regex pattern.