How i can select RQR-1BN6Q360090-0001 (without quotes) using Regex in below -
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
I tried this but it does not work
RptNum=([A-Za-z]+)$
You may use
/RptNum=([\w-]+)/
The pattern will match RptNum= and then capture 1 or more occurrences of word chars (letters, digits and _) or hyphens. See the regex demo and the regex graph:
Note that
/RptNum=([A-Z0-9-]+)/
might be a more restrictive pattern that should work, too. It does not match _ and lowercase letters.
In JS, use it with String#match() and grab the second array item upon a match:
var s = 'Object moved to here';
var m = s.match(/RptNum=([\w-]+)/);
if (m) {
console.log(m[1]);
}
Here, we can also use an expression that collects the new lines, such as:
[\s\S]*RptNum=(.+?)"[\s\S]*
[\w\W]*RptNum=(.+?)"[\w\W]*
[\d\D]*RptNum=(.+?)"[\d\D]*
and our desired output is saved in (.+?).
Test
const regex = /[\s\S]*RptNum=(.+?)"[\s\S]*/gm;
const str = `<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
Demo
RegEx
If this expression wasn't desired, it can be modified/changed in regex101.com.
RegEx Circuit
jex.im visualizes regular expressions:
const text = 'RptNum=RQR-1BN6Q360090-0001';
console.log(text.match(/RptNum=.*/).map(m => m.match(/RptNum=.*/)[0])[0].split('RptNum=')[1]);
I suppose that works
Related
I'm trying to check if a string contains this character `.
And if the character is found, to wrap that string between <div>.
For example:
`this is it
should become:
<div>this is it</div>
And I've tried to do it but it seem to not work:
let arr = "`this is it";
if (arr.includes('`')) {
arr = arr.replace(/\`(\w+)\`/g, '<div>$1</div>');
}
Any ideas?
You can use
arr.replace(/`([^`]+)`?/g, '<div>$1</div>')
The regex matches
` - a backtick
([^`]+) - one or more chars other than backtick
`? - an optional backtick
JavaScript demo
const arrs = ["`test` is `here`","`this is it"];
const regex = /`([^`]+)`?/g;
for (const arr of arrs) {
console.log(arr, '=>', arr.replace(regex, '<div>$1</div>'));
}
I presume that the backtick should only appear at the beginning of the line. If it is also needed at the end, add another one before the $ in the regex.
I also presume that your string is multiline, and any line can start with a backtick. If not, remove the m flag.
If there can be more than one backtick-delimited substrings in a line, make the * quantifier non-greedy with ? and remove the ^ and $ assertions. If such substring can span several lines, also add s flag.
let arr = "`this is it";
arr = arr.replace(/^`(.+)$/mg, '<div>$1</div>');
console.log(arr)
I want to replace {r-group1} with "REPLACED" but leave the , where it is.
So, the string
var string = "{r-group1, }foo bar"
should output: "REPLACED, foo bar"
Using a negative lookahead, I tried adding a preceding (?![,]) group to leave the comma alone:
var replaced = string.replace(^(?:(?![,]){r-group1\})+$, 'REPLACED');
But it returns the same string. There are no matches to replace.
The same goes for a preceding comma:
var string = "foo bar{r-, group1}"
This should output: "foo bar, REPLACED"
You could do the replacement without a lookahead. You could match the curly braces and the content that comes before and after it except a comma using a negated character class [^,}]+ and capture the comma with optional whitespace chars in a capturing group.
In the replacement use the capturing groups $1REPLACED$2
Credits to #Nick for the updated pattern.
{r-(,?\s*)[^,}]+(,?\s*)}
Regex demo
const regex = /{r-(,?\s*)[^,}]+(,?\s*)}/g;
const str = `{r-group1, }foo bar`;
const subst = `$1REPLACED$2`;
const result = str.replace(regex, subst);
console.log(result);
I have a word like this What’s On. How to remove space and ’?
I can remove space like so data.caption.replace(/ +/g, "") How to do the other part?
You can use [] to provide a character set. So in this case, the following would match against the weird quote and a space.
/[’ ]+/g
This expresion might simply work:
\s*’
which checks for 0 or more spaces prior to ’.
console.log("What ’s On ?".replace(/\s*’/,""));
console.log("What ’s On ?".replace(/[\s’]+/,""));
Or if we wish to replace all spaces:
const regex = /([^\s’]+)|(.+?)/gm;
const str = `What ’s On ?`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
Demo
Working in Javascript attempting to use a regular expression to capture data in a string.
My string appears as this starting with the left bracket
['ABC']['ABC.5']['ABC.5.1']
My goal is to get each piece of the regular expression as a chunk or in array.
I have reviewed and see that the match function might be a good choice.
var myString = "['ABC']['ABC.5']['ABC.5.1']";
myString.match(/\[/g]);
The output I see is only the [ for each element.
I would like the array to be like this for example
myString[0] = ['ABC']
myString[1] = ['ABC.5']
myString[2] = ['ABC.5.1']
What is the correct regular expression and or function to get the above-desired output?
If you just want to separate them, you can use a simple expression or better than that you can split them:
\[\'(.+?)'\]
const regex = /\[\'(.+?)'\]/gm;
const str = `['ABC']['ABC.5']['ABC.5.1']`;
const subst = `['$1']\n`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
DEMO
You can use this regex with split:
\[[^\]]+
Details
\[ - Matches [
[^\]]+ - Matches anything except ] one or more time
\] - Matches ]
let str = `['ABC']['ABC.5']['ABC.5.1']`
let op = str.split(/(\[[^\]]+\])/).filter(Boolean)
console.log(op)
I have regexp that extracts values between parentheses.
It's working most of the time but not when it ends with a parentheses
var val = 'STR("ABC(t)")';
var regExp = /\(([^)]+)\)/;.
var matches = regExp.exec(val);
console.log(matches[1]); //"ABC(t"
What I want is "ABC(t)".
Any ideas how I can modify my regexp to Achive this?
Update
The value is always inside the parentheses.
Some examples:
'ASD("123")'; => '123'
'ASD(123)'; => '123'
'ASD(aa(10)asda(459))'; => 'aa(10)asda(459)'
So first there is some text (always text). Then there is a (, and it always ends with a ). I want the value between.
You may use greedy dot matching inside Group 1 pattern: /\((.+)\)/. It will match the first (, then any 1+ chars other than linebreak symbols and then the last ) in the line.
var vals = ['STR("ABC(t)")', 'ASD("123")', 'ASD(123)', 'ASD(aa(10)asda(459))'];
var regExp = /\((.+)\)/;
for (var val of vals) {
var matches = regExp.exec(val);
console.log(val, "=>", matches[1]);
}
Answering the comment: If the texts to extract must be inside nested balanced parentheses, either a small parsing code, or XRegExp#matchRecursive can help. Since there are lots of parsing codes around on SO, I will provide XRegExp example:
var str = 'some text (num(10a ) ss) STR("ABC(t)")';
var res = XRegExp.matchRecursive(str, '\\(', '\\)', 'g');
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/2.0.0/xregexp-all-min.js"></script>