Match number and add before replace - javascript

Suppose I have in text.txt:
prop:"txt1" prop:'txt4' prop:"txt13"
And I want it to become (adding 9):
prop:"txt10" prop:'txt13' prop:"txt22"
In javascript, it would be:
var output = input.replace(/prop:(['"])txt(\d+)\1/g, function(match, quote, number){
return "prop:" + quote + "txt" + (parseInt(number) + 9) + quote;
});
I'm trying to code the above code in C#:
string path = #"C:/text.txt";
string content = File.ReadAllText(path);
File.WriteAllText(path, Regex.Replace(content, "prop:(['\"])txt(\\d+)\\1", ?????));
Visual Studio shows the third parameter should be MatchEvaluator evaluator. But I don't know how to declare/write/use it.
Any help is welcome. Thanks for your time.

You can use a Match evaluator and use Int32.Parse to parse the number as an int value that you can add 9 to:
Regex.Replace(content, #"prop:(['""])txt(\d+)\1",
m => string.Format("prop:{0}txt{1}{0}",
m.Groups[1].Value,
(Int32.Parse(m.Groups[2].Value) + 9).ToString()))
See IDEONE demo:
var content = "prop:\"txt1\" prop:'txt4' prop:\"txt13\"";
var r = Regex.Replace(content, #"prop:(['""])txt(\d+)\1",
m => string.Format("prop:{0}txt{1}{0}",
m.Groups[1].Value,
(Int32.Parse(m.Groups[2].Value) + 9).ToString()));
Console.WriteLine(r); // => prop:"10" prop:'13' prop:"22"
Note that I am using a verbatim string literal so as to use a single backslash to escape special characters and define shorthand character classes (however, in a verbatim string literal a double quote must be doubled to denote a single literal double quote).

MatchEvaluator is a delegate. You need to write a function that takes a Match and returns the replacement value. One way to do this is shown below:
private static string AddEvaluator(Match match)
{
int newValue = Int32.Parse(match.Groups[2].Value) + 9;
return String.Format("prop:{0}txt{1}{0}", match.Groups[1].Value, newValue)
}
public static void Main()
{
string path = #"C:/text.txt";
string content = File.ReadAllText(path);
File.WriteAllText(path, Regex.Replace(content, "prop:(['\"])txt(\\d+)\\1", AddEvaluator));
}

Related

How to convert string to just the values of the string

I want to convert a string such as 'String' to the stripped version of that (I think thats the word?), something like this:
const strip = r => {
/* Code */
}
What I want is:
> strip('String')
> String
basically I just want it to remove the quotes from around a string
(I want the output to be a none-type)
Is this what you are after?
var test = "\"'String \" with 'quotes'\"";
test = test.replace(/['"]/g, "");
console.log("test: " + test);
In your example, the string passed as an argument to the strip function does not have quotes in its content. You're just telling that function that the r parameter is of type string with the content String.
To answer to your question, you can remove the quotes of a string by removing the first and last character:
const strip = str => {
return str.slice(1, -1);
}
strip('"String"') => String

Regex not working for multiple characters

I want to search and replace special characters of markdown (viz \`*_{}[]()#+.!|-) from the given string.
I am able to make it work in C# easily since there is verbatim # but Javascript not getting what's the issue. It seems something to do with /g , I read in another post which asked to use replaceAll but I could not find that method for string
C# version
string test = #"B
*H*
C
**AB**";
Console.WriteLine ("Input " + test);
var pattern = #"[\\`*_{}\[\]()#+-.!]";
var _1 = Regex.Replace (test, "\r?\n", "<br/>");
var out_ = Regex.Replace (_1, pattern, m => #"\" + m.Value);
Console.WriteLine ("Output " + out_);
Typescript Version
const regexM = new RegExp(/[\\\`\*\_\{\}\[\]\(\)#\+-\.!\|]/g, 'm');
var input = `B
*H*
C
**AB**`;
var inputString = input.replace(regexM, function (y: any) { return "\\" + y; });
if (/\r|\n/.exec(inputString))
{
inputString = inputString .replace(/\r?\n/g, "<br/>");
}
inputString = inputString.replace(regexM, function (x: any)
{
return "\\" + x;
});
Expected: B <br/>\*H\*<br/>C<br/>\*\*AB\*\*
I am getting B <br/>\*H*<br/>C<br/>**AB**
You may use
const regexM = /[\\`*_{}[\]()#+.!|-]/g;
var input = `B
*H*
C
**AB**`;
var inputString = input.replace(regexM, "\\$&");
inputString = inputString.replace(/\r?\n/g, "<br/>");
console.log(inputString);
// => B <br/>\*H\*<br/>C<br/>\*\*AB\*\*
NOTE:
The - in the regexM regex forms a range, you need to either escape it or - as in the code above - put it at the end of the character class
Rather than using callback methods, in order to reference the whole match, you may use the $& placeholder in a string replacement pattern
When you define the regex using a regex literal, there is only one backslash needed to form a regex escape, so const regexM = /[\\`*_{}[\]()#+.!|-]/g is equal to const regexM = new RegExp("[\\\\`*_{}[\\]()#+.!|-]", "g")
There is no need to check if there is a line break char or not with if (/\r|\n/.exec(inputString)), just run .replace.

Regex remove underscores from a given string

I try to transform string using String replace method and regular expression. How can I remove underscores in a given string?
let string = 'court_order_state'
string = string.replace(/_([a-z])/g, (_, match) => match.toUpperCase())
console.log(string)
Expected result:
COURT ORDER STATE
You could use JavaScript replace function, passing as input:
/_/g as searchvalue parameter (the g modifier is used to perform a global match, i.e. find all matches rather than stopping after the first one);
(blank space) as newvalue parameter.
let string = 'court_order_state'
string = string.replace(/_/g, ' ').toUpperCase();
console.log(string);
In your code you could match either and underscore or the start of the string (?:_|^) to also match the first word and match 1+ times a-z using a quantifier [a-z]+
Then append a space after each call toUpperCase.
let string = 'court_order_state';
string = string.replace(/(?:_|^)([a-z]+)/g, (m, g1) => g1.toUpperCase() + " ");
console.log(string)
let string = 'court_order_____state'
string = string.replace(/_+/g, ' ').toUpperCase()
console.log(string)
It can be as simple as the below:
let string = 'court_order_state'
string = string.replace(/_/g, ' ').toUpperCase();
console.log(string);
Here the 'g' represents global, whereas the '/' is surrounded by what we're looking for.
Instead of matching the first character just after every _ and making them uppercase (from the regex that you have used), you can simply convert the entire string to uppercase, and replace the _ with space by the following:
let string = 'court_order_state';
string = string.toUpperCase().replace(/_+/g, " ");
console.log(string);

conditional substring in JS

I have a function that should clean a string , actually I have two kind of string "SATISFACTION._IS1.TOUTES_SITUATIONS.current_month_note" or "SATISFACTION._IS1.TOUTES_SITUATIONS.note" .
PS for information TOUTES_SITUATIONS is variable
What I would return is "TOUTES_SITUATIONS"
Here's my code
const extractSituation: Function = (sentence: string): string => {
return sentence.substring(
sentence.lastIndexOf('1.') + 2,
sentence.lastIndexOf('.n'),
);
};
actually it handles only one type of sentence "SATISFACTION._IS1.TOUTES_SITUATIONS.note" but not "SATISFACTION._IS1.TOUTES_SITUATIONS.current_month_note"
How can I do to handle both of them ?
Array's index start from 0. Try something like this:
const extractSituation: Function = (sentence: string): string => {
return sentence.split('.')[2];
};
You might be able to just use a regex for this to pull out the text between the first SATISFACTION._IS1. and last .:
let s = "SATISFACTION._IS1.TOUTES_SITUATIONS.current_month_note"
let s2 = "SATISFACTION._IS1.TOUTES_someother.text__SITUATIONS.note"
let regex = /^SATISFACTION._IS1\.(.*)\..*$/
console.log(s.match(regex)[1])
console.log(s2.match(regex)[1])
I'm assuming:
1) You need to handle a general case where the 'situation' could be any string without periods.
2) The break before and after the 'situation' is delimited by '.'
You can retrieve the substring from the start of the situation to the end of the sentence, then find the index of the next '.' to find the substring containing only the situation.
const extractSituation: Function = (sentence: string): string => {
// sentence truncated up to start of situation
var situation = sentence.substring(sentence.lastIndexOf('1.') + 2);
// Up to the next period from start of situation
return situation.substring(0, situation.indexOf('.'));
};
This code only works given that you can assume every situation is preceded by your '1.' index.

Inserting line numbers using Javascript regex?

suppose a user paste this code in text box :
public static void Main()
{
int a=1+1;
int b=1+1;
}
I want to find in regex all the begining of lines and to add sequentials numbers as : (desired output:)
/*0*/public static void Main()
/*1*/ {
/*2*/ int a=1+1;
/*3*/ int b=1+1;
/*4*/ }
JSBIN : I did managed to do something with :
newVal = oldVal.replace(/^(\b)(.*)/img, function (match, p1, p2, offset, string)
{
return '~NUM~' + p2;
});
But ( 2 problems ) :
it seems that the first group in /^(\b)(.*)/ is not the beginning of the line ,
also it doesnt do it for all rows - although i did specify the m flag.
what am I doing wrong ?
(for now , please leave the sequential numbers ...I will deal with it later. a const string is enough.)
Try to use this:
var str ='public static void Main()\n{\n int a=1+1;\n int b=1+1;\n}',
i=0;
str = str.replace(/^/gm, function (){return '/*'+(++i)+'*/';});
console.log(str);
EDIT: (tribute to Rob W)
A word boundary \b is a zero-width cesure between a character which belongs to the \w class and another character from \W class or an anchor (^ $).
Thus ^\b. will match only when the dot stands for [0-9a-zA-Z_] (or \w).
Notice: A word boundary between to characters, can be replaced with:
.\b. <=> (?=\w\W|\W\w)..
The word boundary does not match because <start of line><whitespace> is not a word boundary.
I would use:
var count = 0;
newVal = oldVal.replace(/^/mg, function() {
return '/*' + (++count) + '*/';
});
\b is a word boundary; you need the start of a line, which is ^ (when used with modifier s). Like this:
var oldval = "public static void Main()\n\
{\n\
int a=1+1;\n\
int b=1+1;\n\
}";
var i = 0;
alert(oldval.replace(/^/mg, function(match) {
return "/*" + (++i) + "*/"; }
));
Try using
regex: ^(\s*.*)
replace with: $Counter . $Matches[1]
Where $Counter is the variable containing your line numbers to be inserted.

Categories