jquery get value in the last instance parenthesis [duplicate] - javascript

I want to extract the text between the last () using javascript
For example
var someText="don't extract(value_a) but extract(value_b)";
alert(someText.match(regex));
The result should be
value_b
Thanks for the help

Try this
\(([^)]*)\)[^(]*$
See it here on regexr
var someText="don't extract(value_a) but extract(value_b)";
alert(someText.match(/\(([^)]*)\)[^(]*$/)[1]);
The part inside the brackets is stored in capture group 1, therefor you need to use match()[1] to access the result.

An efficient solution is to let .* consume everything before the last (
var str = "don't extract(value_a) but extract(value_b)";
var res = str.match(/.*\(([^)]+)\)/)[1];
console.log(res);
.*\( matches any amount of any character until the last literal (
([^)]+) captures one or more characters that are not )
[1] grab captures of group 1 (first capturing group).
use [\s\S] instead of . dot for multiline strings.
Here is a demo at regex101

/\([^()]+\)(?=[^()]*$)/
The lookahead, (?=[^()]*$), asserts that there are no more parentheses before the end of the input.

If the last closing bracket is always at the end of the sentence, you can use Jonathans answer. Otherwise something like this might work:
/\((\w+)\)(?:(?!\(\w+\)).)*$/

Related

how to found 2 matches in regular expression

I need a regular expression for :
<<12.txt>> <<45.txt>
I have created a regular expression :
<<.+.txt>>
But this found one match in whole string but here is 2 matches:
<<12.txt>>
<<45.txt>>
if anyone have solution for this problem please help me out there
Part of the issue is that the string you've specified wouldn't match because the second > is missing in <<45.txt>.
Also, you're using the . (dot) selector, and also trying to find a period. It works, but now how you think it is.
Here's the regex you want:
var regex = /<<\d+\.txt>>/g
\d matches only numbers
\. matches an actual period
/g means global, so it won't stop at the first match
Practice Regular Expressions
https://regexr.com/43bs4
Demo
var string = "<<12.txt>> <<45.txt>>";
var regex = /<<\d+\.txt>>/g;
var matches = string.match(regex);
console.log(matches);
P.S., if you actually want to match with 1 > or 2 >>, you can with:
var regex = /<<\d+\.txt>>?/g
? optionally matches the character right before it
/<<.+.txt>>/gm
g is for global (will search through entire source)
m is for multi line search support

Match two quotes not preceded by opening bracket

I need a regex matching all occurrences of two quotes ('') not preceded by opening bracket ((). I did a negative lookahead for the bracket followed by a quote. But why is this not working:
/(?!\()''/g
for example with this string
(''test''test
It should match the second occurrence but not the first one but it matches both.
When I use exactly the same solution but with check for new line instead of bracket it works fine:
/(?!^)''/g
With this string:
''test''test
It matches as expected only second occurrence.
Tested here
Here is a solution that will work correctly even in case you need to handle consecutive double apostrophes:
var output = "''(''test'''''''test".replace(/(\()?''/g, function($0, $1){
return $1 ? $0 : 'x';
});
document.body.innerHTML = output;
Here, the /(\()?''/g regex searches for all matches with the ( and without, but inside the replace callback method, we check for the Group 1 match. If Group 1 matched, and is not empty, we use the whole match as the replacement text ($0 stands for the whole match value) and if it is not (there is no ( before '') we just insert the replacement.
It's bad that Javascript doesn't support lookback but there is a workaround.
try:
[^\(]('{2,2})
See https://regex101.com/r/gT5jR6/1

JS - Regex for one letter and 6 numbers

I have this regular expression to test if an input starts with the letter "a" and is followed by 6 numbers. On the online validator seems to work, but on JavaScript doesnt.
This is the code:
function checkBookingReference (ref) {
var regex = /(^a|A)([0-9]{6})/;
return regex.test(ref);
}
The function returns true if I enter more than six numbers, and it shouldn't. Any idea why?
That regex will return true if anywhere in the string there is a match. If you want to ensure the entire string matches it, then you'll want to use ^ to match the beginning and $ to match the end.
/^(a|A)([0-9]{6})$/
This is how I would do it:
return /^A[0-9]{6}$/i.test(ref);
Use the regex object to specify the regular expression and then test it. Try this
var regex = new RegExp("^a([0-9]{6})$","i");
return regex.test(ref);
You nee to move the carat ^ outside the parentheses and use a proper group around the letters, then loose the trailing dollar sign $. Try this:
var regex = /^[aA][0-9]{6}/;
The parenthesis inside meant "not". Outside it means "beginning of string". The dollar sign meant "end of string".

javascript regex to return letters only

My string can be something like A01, B02, C03, possibly AA18 in the future as well. I thought I could use a regex to get just the letters and work on my regex since I haven't done much with it. I wrote this function:
function rowOffset(sequence) {
console.log(sequence);
var matches = /^[a-zA-Z]+$/.exec(sequence);
console.log(matches);
var letter = matches[0].toUpperCase();
return letter;
}
var x = "A01";
console.log(rowOffset(x));
My matches continue to be null. Am I doing this correctly? Looking at this post, I thought the regex was correct: Regular expression for only characters a-z, A-Z
You can use String#replace to remove all non letters from input string:
var r = 'AA18'.replace(/[^a-zA-Z]+/g, '');
//=> "AA"
Your main issue is the use of the ^ and $ characters in the regex pattern. ^ indicates the beginning of the string and $ indicates the end, so you pattern is looking for a string that is ONLY a group of one or more letters, from the beginning to the end of the string.
Additionally, if you want to get each individual instance of the letters, you want to include the "global" indicator (g) at the end of your regex pattern: /[a-zA-Z]+/g. Leaving that out means that it will only find the first instance of the pattern and then stop searching . . . adding it will match all instances.
Those two updates should get you going.
EDIT:
Also, you may want to use match() rather than exec(). If you have a string of multiple values (e.g., "A01, B02, C03, AA18"), match() will return them all in an array, whereas, exec() will only match the first one. If it is only ever one value, then exec() will be fine (and you also wouldn't need the "global" flag).
If you want to use match(), you need to change your code order just a bit to:
var matches = sequence.match(/[a-zA-Z]+/g);
To return an array of separate letters remove +:
var matches = sequence.match(/[a-zA-Z]/g);
You're confused about what the goal of the other question was: he wanted to check that there were only letters in his string.
You need to remove the anchors ^$, who match respectively the beginning and end of the string:
[a-zA-Z]+
This will match the first of letters in your input string.
If there might be more (ie you want multiple matches in your single string), use
sequence.match(/[a-zA-Z]+/g)
This /[^a-z]/g solves the problem. Look at the example below.
function pangram(str) {
let regExp = /[^a-z]/g;
let letters = str.toLowerCase().replace(regExp, '');
document.getElementById('letters').innerHTML = letters;
}
pangram('GHV 2## %hfr efg uor7 489(*&^% knt lhtkjj ngnm!##$%^&*()_');
<h4 id="letters"></h4>
You can do this:
var r = 'AA18'.replace(/[\W\d_]/g, ''); // AA
Also can be done by String.prototype.split(regex).
'AA12BB34'.split(/(\d+)/); // ["AA", "12", "BB", "34", ""]
'AA12BB34'.split(/(\d+)/)[0]; // "AA"
Here regex divides the giving string by digits (\d+)

Javascript - return string between square brackets

I need to return just the text contained within square brackets in a string. I have the following regex, but this also returns the square brackets:
var matched = mystring.match("\\[.*]");
A string will only ever contain one set of square brackets, e.g.:
Some text with [some important info]
I want matched to contain 'some important info', rather than the '[some important info]' I currently get.
Use grouping. I've added a ? to make the matching "ungreedy", as this is probably what you want.
var matches = mystring.match(/\[(.*?)\]/);
if (matches) {
var submatch = matches[1];
}
Since javascript doesn't support captures, you have to hack around it. Consider this alternative which takes the opposite approach. Rather that capture what is inside the brackets, remove what's outside of them. Since there will only ever be one set of brackets, it should work just fine. I usually use this technique for stripping leading and trailing whitespace.
mystring.replace( /(^.*\[|\].*$)/g, '' );
To match any text in between two adjacent open and close square brackets, you can use the following pattern:
\[([^\][]*)]
(?<=\[)[^\][]*(?=])
See the regex demo #1 and regex demo #2. NOTE: The second regex with lookarounds is supported in JavaScript environments that are ECMAScript 2018 compliant. In case older environments need to be supported, use the first regex with a capturing group.
Details:
(?<=\[) - a positive lookbehind that matches a location that is immediately preceded with a [ char (i.e. this requires a [ char to occur immediately to the left of the current position)
[^\][]* - zero or more (*) chars other than [ and ] (note that ([^\][]*) version is the same pattern captured into a capturing group with ID 1)
(?=]) - a positive lookahead that matches a location that is immediately followed with a ] char (i.e. this requires a ] char to occur immediately to the right of the current regex index location).
Now, in code, you can use the following:
const text = "[Some text] ][with[ [some important info]";
console.log( text.match(/(?<=\[)[^\][]*(?=])/g) );
console.log( Array.from(text.matchAll(/\[([^\][]*)]/g), x => x[1]) );
// Both return ["Some text", "some important info"]
Here is a legacy way to extract captured substrings using RegExp#exec in a loop:
var text = "[Some text] ][with[ [some important info]";
var regex = /\[([^\][]*)]/g;
var results=[], m;
while ( m = regex.exec(text) ) {
results.push(m[1]);
}
console.log( results );
Did you try capturing parens:
("\\[(.*)]");
This should return the pattern within the brackets as a captured match in the returned array
Just use replace and map
"blabla (some info) blabla".match(/\((.*?)\)/g).map(b=>b.replace(/\(|(.*?)\)/g,"$1"))
You can't. Javascript doesn't support lookbehinds.
You'll have to either use a capture group or trim off the brackets.
By the way, you probably don't want a greedy .* in your regex. Try this:
"\\[.*?]"
Or better, this:
"\\[[^\\]]*]"

Categories

Resources