How to manipulate regex named capturing groups - node.js

I'm trying to use a capture group to replace data with itself, plus a manipulation to a number in it. This is the text to work on:
firstGroup1
firstGroup33
My goal is to replace any number of group with itself + 1 to get, for example:
firstGroup2
firstGroup34
This currently is the code to display the two different capture groups:
data = data.replace(/(firstGroup)([1])/gms, '$1 $2')
and this is a failed attempt to do what I want, for sakes of understanding the question:
data = data.replace(/(firstGroup)([1])/gms, '$1' + $2+1
How can I perform this number addition in nodeJS javascript? thank you!
example 2:
text:
.method public constructor <init>()V
.locals 2
failed code:
data = data.replace(/(constructor \<init\>[(][)]V.............)(..)/gms, (_, first, num) => first + (Number(num) + 1));

You don't have any named capturing groups here, only plain capturing groups - use a replacer function that replaces with the first captured group, concatenated with the second capturing group cast to a number plus 1:
const data = `firstGroup1
firstGroup33`;
const result = data.replace(
/(firstGroup)(\d+)/g,
(_, first, num) => first + (Number(num) + 1)
);
console.log(result);
Because you aren't using the . to match spaces anywhere in the pattern, there's no need for the s modifier, nor are you using ^ or $, so no need for the m modifier either.
(A named capturing group looks something like:
const str = 'foo bar';
const match = str.match(/foo (?<whatComesAfterFoo>\S+)/);
console.log(match.groups.whatComesAfterFoo);
)

Related

adding commas and removing space after each class is copied cheerio

i am not understanding how can add commas after each class is copied i did it using for loop but it gives more different output than I want. There are around 9 div class of .name so when each one is copied i want add commas and remove extra space.
here is my code part:
const A = $('.tag-container.field-name').map((i, section) => {
let B = $(section).find('.name')
return B.text()
})
.get(2)
console.log(A)
Use trim and join:
$(css).get().map(el => $(el).text().trim()).join(', ')
There are two things you want to do here.
To remove any whitespace from the left or right-hand sides of a string (eg. from " foo " to "foo"), you can use the String.trim() method.
Regarding the second point, I assume that in adding commas, you want to end up with a string of classnames, separated with commas, like "foo,bar,baz". The .map method you are already using will return an array of something. You can join elements of an array together as a string with the Array.join() method. The join method takes a single argument which specifies the string to use in between each element.
Put those together, and you end up with something like:
const A = $(".tag-container.field-name")
.map((i, section) => {
let B = $(section).find(".name");
return B.text().trim(); // Note use of trim
})
.join(',') // Join all elements of the array with the `,` character
console.log(A);
// Something like `"foo,bar,baz"`

Groovy replace everything after character

I need to replace all content after a specific character in groovy with the value of a parameter,
my string is :
env.APP_VERSION="1.9"
And I would like to replace everything after the = sign with the value of a certain parameter let's call it $PARAM.
I was able to trim everything after the = sign,
but not replace it...
result = result.substring(0, result.indexOf('APP_VERSION='));
any help would be appreciated.
One of possible solutions is, indeed, to use regex. It should include:
(?<==) - A positive lookbehind for =.
.* - Match all chars (up to the end).
So the script can look like below:
src = 'env.APP_VERSION="1.9"'
PARAM = '"xyz"'
res = src.replaceFirst(/(?<==).*/, PARAM)
Another solution is to split the string on = and "mount" the result string
from:
The first string from split result.
= char.
Your replacement string.
This time the processing part of the script should be:
spl = src.split('=')
res = spl[0] + '=' + PARAM
Without knowing about your original intentions you have 2 options:
1) Do not reinvent the wheel and use GString magic:
String ver = '1.9'
String result = "env.APP_VERSION=\"$ver\""
2) use some regex:
result = result.replaceFirst( /APP_VERSION="[^"]+"/, 'APP_VERSION="something"' )

Regex to capture comma separated numbers enclosed in quotes

I have a large set of JavaScript snippets each containing a line like:
function('some string without numbers', '123,71')
and I'm hoping to get a regex together to pull the numbers from the second argument. The second argument can contain an arbitrary number of comma separated numbers (inlcuding zero numbers), so the following are all valid:
''
'2'
'17,888'
'55,1,6000'
...
The regex '(?:\d+|,)*' successfully matches the quoted numbers, but I have no idea how to match each of the numbers. Placing a capture group around the \d+ seems to capture the last number (if there is one present -- it doesn't work if the second argument is just ''), but none of the others.
In your case, you may match and capture the digits inside the single quotes and then split them with a comma:
var s = "function('some string without numbers', '123,71')";
var res = s.match(/'([\d,]+)'/) || ["", ""];
console.log(res[1].split(','));
The /'([\d,]+)'/ regex will match a ', then 1+ digits or commas (placing that value into Group 1) and then a closing '.
If you want to run the regex globally, use
var s = "function('some string without numbers', '123,71')\nfunction('some string without numbers', '13,4,0')";
var rx = /'([\d,]+)'/g;
var res = [], m;
while ((m=rx.exec(s)) !== null) {
res.push(m[1].split(','));
}
console.log(res);
If you have a numbers in a variable x like this:
var x = '55,1,6000';
then use this to have the list of numbers:
var array = x.split(',');
If you can have some whitespace before/after the comma then use:
var array = x.split('\s*,\s*');
or something like that.
Sometimes it is easier to match the thing that you don't want and split on that.

Replacing Numeric Characters through Indexing

I'm attempting to replace a character within a string, which in this case is a digit, with another digit that has been incremented by 1, and then adding it back to the original string and replacing the previous digit character.
In the below snippet, sams2 should become sams3 after this code has executed
However, I keep receiving the error, Unable to index into an object of type System.String. Is it not possible to replace characters through indexing? Is there a better methodology for something like this?
$SAMAccountName = "sams2"
$lastChar = $SAMAccountName.Length - 1
[int]$intNum = [convert]::ToInt32($SAMAccountName[$lastChar])
$convertedChar = [convert]::ToString($intNum + 1)
$SAMAccountName[$lastChar] = $convertedChar
This would only work if the incremental number is one digit.
$SAMAccountName = "sams2"
$partOne = $SAMAccountName.SubString(0, $SAMAccountName.Length - 1)
$partTwo = [int]$SAMAccountName.SubString($SAMAccountName.Length - 1, 1) + 1
$SAMAccountName = "$partOne$partTwo"
Ok, this is a two step process. First we get the number off the end, then we replace that number in the string.
'sams2' |%{
$Int = 1+ ($_ -replace "^.*?(\d+)$",'$1')
$_ -replace "\d+$",$Int
}
Maybe try regular expressions and groups and then be able to handle multi-digits for free...
$SAMAccountName = "sam2"
# use regex101.com for help with regular expressions
if ($SAMAccountName -match "(.*?)(\d+)")
{
# uncomment for debugging
#$Matches
$newSAMAccountName = $Matches[1] + (([int]$Matches[2])+1)
$newSAMAccountName
}
There are a couple of things to note in your code:
Strings are immutable. New instance of string is created every time some change is made.
Use StringBuilder to manipulate individual chars.
Make sure you have compatible types. String is not char.
Take a look at following snippet:
$SAMAccountName = "sams2"
$sb = [System.Text.StringBuilder]$SAMAccountName
$lastChar = $SAMAccountName.Length - 1
[int]$intNum = [convert]::ToInt32($SAMAccountName[$lastChar])
$covertedChar = [convert]::ToChar($intNum + 1)
$sb[$lastChar] = $covertedChar
[string]$sb
You can also use another metod, like following one:
$SAMAccountName = "sams2"
$SAMAccountName.Substring(0, $SAMAccountName.Length-1)+([int]$SAMAccountName.Substring($SAMAccountName.Length-1, 1)+1)

Get indexOf special characters in ActionScript3

In ActionScript3 i wanted to get the text between 2 quotes from some HTML using a input index value where i would simply increase the 2nd quote characters value by 1. This would be very simple however i have now noticed using indexOf does not seem to work correctly with quotes and other special characters.
So my question is if you have some HTML style text like this:
var MyText:String = '<div style="text-align:center;line-height:150%"><a href="http://www.website.com/page.htm">';
How can i correctly get the index of a quote " or other special character?
Currently i try this:
MyText.indexOf('"',1)
but after 0 it always returns the wrong index value.
Also a quick additional question would be is there a better way than using ' ' to store strings with characters like " inside? So if i had other ' characters etc it won't cause problems.
Edit -
This is the function i had created (usage = GetQuote(MyText,0) etc)
// GetQuote Function (Gets the content between quotes at a set index value)
function GetQuote(Input:String, Index:Number):String {
return String(Input.substr(Input.indexOf('"', Index), Input.indexOf('"', Index + 1)));
}
The return for GetQuote(MyText,0) is "text-align yet i need text-align:center;line-height:150% instead.
First off, index of the first quote is 11 and both MyString.indexOf('"') and MyString.indexOf('"',1) return the right value (the latter also works because you don't actually have a quote at the beginning of your string).
When you need to use an single quote inside another one or a double quote inside another one you need to escape the inner one(s) using backslashes. So to catch a single quote you would use it like '\''
There are several ways of stripping a value from a string. You can use the RegExp class or use standard String functions like indexOf, substr etc.
Now what exactly would you like the result to become? Your question is not obvious.
EDIT:
Using the RegExp class is much easier:
var myText:String = '<div style="text-align:center;line-height:150%"><a href="http://www.website.com/page.htm">';
function getQuote(input:String, index:int=0):String {
// I declared the default index as the first one
var matches:Array = [];
// create an array for the matched results
var rx:RegExp = /"(\\"|[^"])*"/g;
// create a RegExp rule to catch all grouped chars
// rule also includes escaped quotes
input.replace(rx,function(a:*) {
// if it's "etc." we want etc. only so...
matches.push(a.substr(1,a.length-2));
});
// above method does not replace anything actually.
// it just cycles in the input value and pushes
// captured values into the matches array.
return (index >= matches.length || index < 0) ? '' : matches[index];
}
trace('Index 0 -->',getQuote(myText))
trace('Index 1 -->',getQuote(myText,1))
trace('Index 2 -->',getQuote(myText,2))
trace('Index -1 -->',getQuote(myText,-1))
Outputs:
Index 0 --> text-align:center;line-height:150%
Index 1 --> http://www.website.com/page.htm
Index 2 -->
Index -1 -->

Resources