I have a string from which I need to extract specific texts
let str = 'id = "Test This is" id ="second" abc 123 id ="third-123"';
let res = str.match(/[^id ="\[](.*)[^\]]/g);
console.log(res);
I want the texts in ids only ['Test This is','second','third-123']
But I am getting [ 'Test This is" id ="second" abc 123 id ="third-123"' ]
The whole text after first id which I don't want.I need help with the pattern.
Your pattern uses a negated character class where you exclude matching the listed individual characters, and also exclude matching [ and ] which are not present in the example data.
That way you match the first char T in the string with [^id ="\[] and match the last char ; in the string with [^\]] and the .* captures all in between.
I would suggest using a negated character class to exclude matching the " instead:;
\bid\s*=\s*"([^"]*)"
Regex demo
let str = 'id = "Test This is" id ="second" abc 123 id ="third-123"';
let res = str.matchAll(/\bid\s*=\s*"([^"]*)"/g);
console.log(Array.from(str.matchAll(/\bid\s*=\s*"([^"]*)"/g), m => m[1]));
You can simplify this down to a non-greedy regular expression indepedent of where the quotes fall in the string:
let str = 'id = "Test This is" id ="second" abc 123 id ="third-123"';
let res = str.match(/".*?"/g);
console.log(res);
Related
My string looks like this street no [12]
I need to extract the 12 alone from the string.
How do I get the substring between two [ ] in javascript or jquery?
find the substring between first matching [] brackets
I noted that your requirements changed in a comment below the previous answer, to fix that issue you can change the regex adding ? so it will capture the least possible matches.
const myString = "street no [12][22]"
const match = myString.match(/\[(.+?)\]/);
const myNumber = match && match[1];
console.log(myNumber);
Or, you can just capture digits if that works better for your needs
const myString = "street no [12][22]"
const match = myString.match(/\[(\d+)\]/);
const myNumber = match && match[1];
console.log(myNumber);
You can use a regular expression for this:
const myString = "street no [12]"
const match = myString.match(/\[(.+)\]/);
const myNumber = match && match[1];
console.log(myNumber);
I'm struggling with a regex.
I am able to split the string at the required location, but when it is added to an array, the array has an empty string at the start.
// This is the string I am wanting to split.
// I want the first 4 words to be separated from the remainder of the string
const chatMessage = "This is a string that I want to split";
// I am using this regex
const r = /(^(?:\S+\s+\n?){4})/;
const chatMessageArr = chatMessage.split(r);
console.log(chatMessageArr);
It returns:
[ '', 'This is a string ', 'that I want to split' ]
But need it to return:
[ 'This is a string ', 'that I want to split' ]
I wouldn't use string split here, I would use a regex replacement:
var chatMessage = "This is a string that I want to split";
var first = chatMessage.replace(/^\s*(\S+(?:\s+\S+){3}).*$/, "$1");
var last = chatMessage.replace(/^\s*\S+(?:\s+\S+){3}\s+(.*$)/, "$1");
console.log(chatMessage);
console.log(first);
console.log(last);
Add a second capture group to the regexp and use .match() instead of .split().
// This is the string I am wanting to split.
// I want the first 4 words to be separated from the remainder of the string
const chatMessage = "This is a string that I want to split";
// I am using this regex
const r = /(^(?:\S+\s+\n?){4})(.*)/;
const chatMessageArr = chatMessage.match(r);
chatMessageArr.shift(); // remove the full match
console.log(chatMessageArr);
let str = 'text text example.com/?isExample=true more text'
if (str.match(/.com/i)) {
...
}
How can I get the whole example.com link based on just that one condition? I need only the link, not the text as well.
So the expected result would be example.com/?isExample=true
Here's one solution: Use a positive lookahead assertion, (?=…[your condition here]…) followed by the whole pattern you want to match.
let str = 'text text example.com/?isExample=true more text'
console.log(str.match(/(?=\S*\.com)\S+/i));
This will match any sequence of one or more non-whitespace characters (\S+) so long as that sequence contains a subsequence that matches your condition. The \S* inside the assertion means that the matched subsequence may begin anywhere within the sequence, not just at the beginning.
Figured out it works best for me this way:
let str = 'asdsadf example.com/?isExample=true adpdor'
str.split(/\s/).forEach(word => {
if (word.match(/.com/i)) console.log(word)
})
You can use \S+\.com.\S+
let re = new RegExp(/\S+\.com.\S+/),
str = "text text example.com/?isExample=true more text",
result = str.match(re);
console.log(result);
You can use following regex
let str = 'text text example.co.in/?isExample=true&y=3 more text'
let res = str.match(/\w+(\.[a-z]{2,3})+\/?\??(\w+=\w+&?)*/)[0];
console.log(res)
for example i have this two strings:
string1:
"hi sir may name is Jone"
string2
"hi may name is Jone"
i have this this regex:
var regex = XRegExp('hi(?:(?!hi|Jone).)*?Jone', 'gs');
will match both of them but i want to modify the regex to match only in limited length of the whole string
i want to match the string two "hi may name is Jone" as had less words length how to do it..
If you want to get the string with the least amount of words that also matches your regex, you could split and use a whitespace as a separator and check the length of the returned array.
As an example with an array of strings, you could create var longestString = ""; which will at the end of the loop contain the shortest matched string.
In the loop, first check if there is a match and if longestString is an empty string. If that is the case then set the variable so you have a match to compare against future possible matches.
var strings = [
"test",
"hi sir may name is Jone",
"hi may name is Jone",
"hi Jone",
"hi may name is Jone test",
"hi i am Jone",
"may name is Jone test",
"hi may name is Jane test test 2"
];
var regex = /hi(?:(?!hi|Jone).)*?Jone/;
var longestString = "";
strings.forEach((str) => {
var match = XRegExp.match(str, regex);
if (match && longestString === "") {
longestString = str;
return;
}
if (match && str.split(" ").length < longestString.split(" ").length) {
longestString = str;
}
});
console.log(longestString);
<script src="https://unpkg.com/xregexp/xregexp-all.js"></script>
If you want to match a limited length of the whole string using only regex, I think you can do something like this:
var index = 15;
var testString1 = "hi may name is Jone";
var testString2 = "hi sir may name is Jone";
testString1.match("^.{1," + index + "}Jone"); // This will match
testString2.match("^.{1," + index + "}Jone"); // This string is longer and will not match
Explanation of the regex ^.{1, n}Jone.
^ : should match the start of the string.
.{1, n}Jone : matches everything between 1 to n until the pattern is fully matched.
In this case we define the n as index so this "limit" can be dynamic.
Hope this helps!
I have this string (notice the multi-line syntax):
var str = ` Number One: Get this
Number Two: And this`;
And I want a regex that returns (with match):
[str, 'Get this', 'And this']
So I tried str.match(/Number (?:One|Two): (.*)/g);, but that's returning:
["Number One: Get this", "Number Two: And this"]
There can be any whitespace/line-breaks before any "Number" word.
Why doesn't it return only what is inside of the capturing group? Am I misundersating something? And how can I achieve the desired result?
Per the MDN documentation for String.match:
If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null.
(emphasis mine).
So, what you want is not possible.
The same page adds:
if you want to obtain capture groups and the global flag is set, you need to use RegExp.exec() instead.
so if you're willing to give on using match, you can write your own function that repeatedly applies the regex, gets the captured substrings, and builds an array.
Or, for your specific case, you could write something like this:
var these = str.split(/(?:^|\n)\s*Number (?:One|Two): /);
these[0] = str;
Replace and store the result in a new string, like this:
var str = ` Number One: Get this
Number Two: And this`;
var output = str.replace(/Number (?:One|Two): (.*)/g, "$1");
console.log(output);
which outputs:
Get this
And this
If you want the match array like you requested, you can try this:
var getMatch = function(string, split, regex) {
var match = string.replace(regex, "$1" + split);
match = match.split(split);
match = match.reverse();
match.push(string);
match = match.reverse();
match.pop();
return match;
}
var str = ` Number One: Get this
Number Two: And this`;
var regex = /Number (?:One|Two): (.*)/g;
var match = getMatch(str, "#!SPLIT!#", regex);
console.log(match);
which displays the array as desired:
[ ' Number One: Get this\n Number Two: And this',
' Get this',
'\n And this' ]
Where split (here #!SPLIT!#) should be a unique string to split the matches. Note that this only works for single groups. For multi groups add a variable indicating the number of groups and add a for loop constructing "$1 $2 $3 $4 ..." + split.
Try
var str = " Number One: Get this\
Number Two: And this";
// `/\w+\s+\w+(?=\s|$)/g` match one or more alphanumeric characters ,
// followed by one or more space characters ,
// followed by one or more alphanumeric characters ,
// if following space or end of input , set `g` flag
// return `res` array `["Get this", "And this"]`
var res = str.match(/\w+\s+\w+(?=\s|$)/g);
document.write(JSON.stringify(res));