I am working in Go, I have a text file in which I want to replace a text based on a regex, but it's not working as expected even when I already tested the regex here and it says that there's a match.
I made the basic example in play ground and I am getting the same result. I have 3 text files with the same label (//==start== and //==end==), it works for the first one, but no for the second and third. What can be avoiding the regex to replace correctly the text?
https://play.golang.org/p/nZdHg5IfZ89
This is the code that I used, I pasted all the string because I want to be sure that it's not the one affecting me
package main
func main() {
var re = regexp.MustCompile(Myregex)
s := re.ReplaceAllLiteralString(originalString,"replaced")
fmt.Println(s)
}
var Myregex = `\/\/==start==\n(.+\n)*\/\/==end==`
var originalString = `// #Author: someone
// #Date: 2018-01-23T16:46:09-04:00
// #Email: dddddddd#gmail.com
// #Filename: _material.themes.scss
// #Last modified by: Someone
// #Last modified time: 2018-01-23T18:40:39-04:00
#include angular-material-theme($theme);
.app-dark {
#include angular-material-theme($dark-theme);
}
.app-pink {
#include angular-material-theme($pink-theme);
}
//==start==
//==end==`
Hope this will help you
func main() {
var re = regexp.MustCompile(Myregex)
s := re.ReplaceAllString(originalString, "replaced")
fmt.Println(s)
}
var Myregex = `//==start==\n.*\n//==end==`
See in action: https://play.golang.org/p/GITAdHOOQOg
Related
I'm been running into weird issues with regex and Typescript in which I'm trying to have my expression replace the value of test minus the first instance if followed by test. In other words, replace the first two lines that have test but for the third line below, replace only the second value of test.
[test]
[test].[db]
[test].[test]
Where it should look like:
[newvalue]
[newvalue].[db]
[test].[newvalue]
I've come up with lots of variations but this is the one that I thought was simple enough to solve it and regex101 can confirm this works:
\[(\w+)\](?!\.\[test\])
But when using Typescript (custom task in VSTS build), it actually replaces the values like this:
[newvalue]
[newvalue].[db]
[newvalue].[test]
Update: It looks like a regex like (test)(?!.test) breaks when changing the use cases removing the square brackets, which makes me think this might be somewhere in the code. Could the problem be with the index that the value is replaced at?
Some of the code in Typescript that is calling this:
var filePattern = tl.getInput("filePattern", true);
var tokenRegex = tl.getInput("tokenRegex", true);
for (var i = 0; i < files.length; i++) {
var file = files[i];
console.info(`Starting regex replacement in [${file}]`);
var contents = fs.readFileSync(file).toString();
var reg = new RegExp(tokenRegex, "g");
// loop through each match
var match: RegExpExecArray;
// keep a separate var for the contents so that the regex index doesn't get messed up
// by replacing items underneath it
var newContents = contents;
while((match = reg.exec(contents)) !== null) {
var vName = match[1];
// find the variable value in the environment
var vValue = tl.getVariable(vName);
if (typeof vValue === 'undefined') {
tl.warning(`Token [${vName}] does not have an environment value`);
} else {
newContents = newContents.replace(match[0], vValue);
console.info(`Replaced token [${vName }]`);
}
}
}
Full code is for the task I'm using this with: https://github.com/colindembovsky/cols-agent-tasks/blob/master/Tasks/ReplaceTokens/replaceTokens.ts
For me this regex is working like you are expecting:
\[(test)\](?!\.\[test\])
with a Typescript code like that
myString.replace(/\[(test)\](?!\.\[test\])/g, "[newvalue]");
Instead, the regex you are using should replace also the [db] part.
I've tried with this code:
class Greeter {
myString1: string;
myString2: string;
myString3: string;
greeting: string;
constructor(str1: string, str2: string, str3: string) {
this.myString1 = str1.replace(/\[(test)\](?!\.\[test\])/g, "[newvalue]");
this.myString2 = str2.replace(/\[(test)\](?!\.\[test\])/g, "[newvalue]");
this.myString3 = str3.replace(/\[(test)\](?!\.\[test\])/g, "[newvalue]");
this.greeting = this.myString1 + "\n" + this.myString2 + "\n" + this.myString3;
}
greet() {
return "Hello, these are your replacements:\n" + this.greeting;
}
}
let greeter = new Greeter("[test]", "[test].[db]", "[test].[test]");
let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
alert(greeter.greet());
}
document.body.appendChild(button);
Online playground here.
I am developing a little hobby project trying to bring C# down to be compilable to the NES over at this repository. As of commit 9b532f739be some of the unit tests on my first Code Fix Provider are failing only because Roslyn is ignoring the Whitespace trivia that is coming from a node that I want replaced, in line 90 of the ForbidMuliplicationCodeFixProvider.cs file. I've also tried NormalizeWhiteSpace on the new node with the same WhiteSpaceTrivia indent size, and a couple other failed attemps, only to always end up with standard tab-size indents on the modified document. Will I have to live with this little bug?
var assignment = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, variableIdentifier, invocation);
assignment = assignment.WithTriviaFrom(node);
var syntaxRoot = await document.GetSyntaxRootAsync();
var modifiedRoot = syntaxRoot.ReplaceNode(node, assignment);
var modifiedDocument = document.WithSyntaxRoot(modifiedRoot);
modifiedDocument = await AddUsingStatementAsync(cancelToken, modifiedDocument);
return modifiedDocument;
The node variable comes from the original document with 6 spaces (3 tiers of indentation) of WhiteSpaceTrivia, which are supposed to be copied into the replacement node but the output of the modified document has 3 tabs of indentation instead.
My test fails with this message:
The checked string has different spaces than expected one. At line 7, col 12, expected '... test = NESMath....' was '... test = NE...'.
The checked string:
["using NINNES.Platform.Shims;
namespace NINNES.RoslynAnalyzers.Tests.Assets {
class MultiplicationAssignment {
public void Multiply() {
var test = 2;
test = NESMath.Multiply(test, 42);
}
}
}
"]
The expected string:
["using NINNES.Platform.Shims;
namespace NINNES.RoslynAnalyzers.Tests.Assets {
class MultiplicationAssignment {
public void Multiply() {
var test = 2;
test = NESMath.Multiply(test, 42);
}
}
}
"]
As an aside: Commentary on the Roslyn code would be greatly appreciated, just learning the ropes of the code modification stuff.
I have a meteor app for which I added the search-source package to search certain collections and it works partially. That is, when I search for the term foo bar it returns results for each of "foo" and "bar". This is fine, but I want to also be able to wrap the terms in quotes this way: "foo bar" and get results for an exact match only. at the moment when i do this i get an empty set. Here is my server code:
//Server.js
SearchSource.defineSource('FruitBasket', function(searchText, options) {
// options = options || {}; // to be sure that options is at least an empty object
if(searchText) {
var regExp = buildRegExp(searchText);
var selector = {$or: [
{'fruit.name': regExp},
{'fruit.season': regExp},
{'fruit.treeType': regExp}
]};
return Basket.find(selector, options).fetch();
} else {
return Basket.find({}, options).fetch();
}
});
function buildRegExp(searchText) {
// this is a dumb implementation
var parts = searchText.trim().split(/[ \-\:]+/);
return new RegExp("(" + parts.join('|') + ")", "ig");
}
and my client code:
//Client.js
Template.dispResults.helpers({
getPackages_fruit: function() {
return PackageSearch_fruit.getData({
transform: function(matchText, regExp) {
return matchText.replace(regExp, "<b>$&</b>")
},
sort: {isoScore: -1}
});
}
});
Thanks in advance!
I've modified the .split pattern so that it ignores everything between double quotes.
/[ \-\:]+(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/
Thus, you can simply wrap an exact phrase search in double quotes and it won't get split.
There is one more thing; since we don't need the quotes, they are removed in the next line using a .map function with a regex that replaces double quotes at the start or the end of a string part: /^"|"$/
Sample code:
function buildRegExp(searchText) {
// exact phrase search in double quotes won't get split
var arr = searchText.trim().split(/[ \-\:]+(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/);
var parts = arr.map(function(x){return x.replace(/^"|"$/g, '');});
return new RegExp("(" + parts.join('|') + ")", "ig");
}
console.log(buildRegExp("foo bar"));
console.log(buildRegExp("\"foo bar\""));
The output in the log should be " scripting" because these are the next 10 characters followed by the search criteria "general-purpose". Please visit www.php.net to see what I mean, you will find the search string "general-purpose" on top of www.php.net. I think that I have done some more mistakes in this piece of code, right?
function parse() {
// parse site and store html in response
var response = UrlFetchApp.fetch('www.php.net').getContentText();
// declare search string and new regex object
var str = "/general-purpose/+10-following-charcters";
var regExp = new RegExp("/general-purpose/.{0,10}", "gi");
// find the string "general-purpose" and store the next 10 characters in response
var response = regExp.exec(str[0]);
// expected result in logger output is " scripting"
Logger.log(response);
}
It should be general-purpose(.{0,10}) and not /general-purpose/.{0,10}.
Also regExp.exec(str[0]) should be regExp.exec(str)[1].
This code seems to work fine
var str = UrlFetchApp.fetch('www.php.net').getContentText();
var regExp = new RegExp("general-purpose(.{0,10})", "gi");
var response = regExp.exec(str)[1];
Logger.log(response);
I am trying to get the following working code in JavaScript also working in Dart.
https://jsfiddle.net/8xyxy8jp/1/
var s = "We live, on the # planet earth";
var results = s.replace(/[^\w]+/g, '-');
document.getElementById("output").innerHTML = results;
Which gives the output
We-live-on-the-planet-earth
I have tried this Dart code
void main() {
print( "We live, on the # planet earth".replaceAll("[^\w]+","-"));
}
But the output becomes the same.
What am I missing here?
If you want replaceAll() to process the argument as regular expression you need to pass a RegExp instance. I usually use r as prefix for the regex string to make it a raw string where not interpolation ($, \, ...) takes place.
main() {
var s = "We live, on the # planet earth";
var result = s.replaceAll(new RegExp(r'[^\w]+'), '-');
print(result);
}
Try it in DartPad