I have a file with the following content
aaaaa(fasdfiojasdlfkj)
213.df(fasdfsadffdfsd)
53434534535(oipowerier)
2.3.*12.4(asdfrwer)
i would like to have a list like this eventually,
List<string[]> sList = new List<string[]>();
sList[0] = new string[]{"aaaaa", "fasdfiojasdlfkj"};
sList[1] = new string[]{"213.df", "fasdfsadffdfsd"};
sList[2] = new string[]{"53434534535", "oipowerier"};
sList[3] = new string[]{"2.3.*12.4", "asdfrwer"};
You can do this without regex:
var result = stringlist.ConvertAll(x =>x.Split(new char[] {'(',')'},
StringSplitOptions.RemoveEmptyEntries));
You don't need Regex for this - string.Split will be enough.
If you use it per line:
List<string[]> sList = new List<string[]>();
foreach(var line in fileLines)
{
sList.Add(line.Split(new Char[]{ '(', ')'},
StringSplitOptions.RemoveEmptyEntries));
}
List<string[]> sList = new List<string[]>();
MatchCollection matches = Regex.Matches(yourtext, #"([^\(]+)\(([^\)]+)\)");
foreach(Match mymatches in matches)
{
//get the data
string firststring = mymatches.Groups[1].Value;
string secondstring = mymatches.Groups[2].Value;
sList.Add(new string[] {firststring, secondstring});
}
not tested though....
Related
I would like to make this code shorter and cleaner.
This code works properly, but It is to long for me:
String givenWord = "help";
String partA = givenWord.replace("a", "1");
String partB = partA.replace("b", "2");
String partC = partB.replace("c", "10");
String partD = partC.replace("d", "11");
String partE = partD.replace("e", "12");
String partF = partE.replace("f", "20");
String partG = partF.replace("g", "21");
String partH = partG.replace("h", "22");
String partI = partH.replace("i", "100");
String partJ = partI.replace("j", "101");
String partK = partJ.replace("k", "102");
String partL = partK.replace("l", "110");
String partM = partL.replace("m", "111");
String partN = partM.replace("n", "112");
String partO = partN.replace("o", "120");
String partQ = partO.replace("q", "121");
String partP = partQ.replace("p", "122");
String partR = partP.replace("r", "200");
String partS = partR.replace("s", "201");
String partT = partS.replace("t", "202");
String partU = partT.replace("u", "210");
String partV = partU.replace("v", "211");
String partW = partV.replace("w", "212");
String partX = partW.replace("x", "220");
String partY = partX.replace("y", "221");
String partZ = partY.replace("z", "222");
System.out.println(partZ);
I need to replace all letters in the given word like that:
The output is 2220110122.
I have tried to use 'for loops' and other methods, but they didn't work well.
I am a beginner, that's why I am asking here :)
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'm just getting started with CoreNLP's TokenSequencePattern and I can't get simple matches to work. All im trying to do is to match a token from the input text. The code below executes without errors but doesn't match anything. However, if u change the match expression to [] then it matches the two sentences.
Properties props = new Properties();
props.put("annotators", "tokenize, ssplit, parse");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Annotation document = new Annotation("This is sent 1. And here is sent 2");
pipeline.annotate(document);
List<CoreMap> sentences = document.get(CoreAnnotations.SentencesAnnotation.class);
Env env = TokenSequencePattern.getNewEnv();
env.setDefaultStringMatchFlags(NodePattern.CASE_INSENSITIVE);
env.setDefaultStringPatternFlags(Pattern.CASE_INSENSITIVE);
TokenSequencePattern pattern = TokenSequencePattern.compile(env,"[ { word:\"sent\" } ]");
TokenSequenceMatcher matcher = pattern.getMatcher(sentences);
while ( matcher.find() ) {
System.out.println( matcher.group() );
}
Thank you!
List<CoreLabel> tokens =
document.get(CoreAnnotations.TokensAnnotation.class);
TokenSequencePattern pattern= TokenSequencePattern.compile("[ {
word:\"sent\" } ]");
TokenSequenceMatcher matcher = pattern.getMatcher(tokens);
while (matcher.find())
{
String matchedString = matcher.group();
List<CoreMap> matchedTokens = matcher.groupNodes();
System.out.println(matchedString + " " + matchedTokens);
}
I have file name like
C:\fakepath\CI_Logo.jpg.
I need a regex for getting CI_Logo.jpg. Tried with \\[^\\]+$, but didn't workout..
Below is my Javascript Code
var regex="\\[^\\]+$";
var fileGet=$('input.clsFile').val();
var fileName=fileGet.match(regex);
alert(fileName);
Minimalist approach: demo
([\w\d_\.]+\.[\w\d]+)[^\\]
Use this
String oldFileName = "slashed file name";
String[] fileNameWithPath = oldFileName.split("\\\\");
int pathLength = fileNameWithPath.length;
oldFileName = fileNameWithPath[pathLength-1];
in java,
I guess,You can modify this for any other langs.
Edit:
make sure you split with "\\\\" - four slashes
Ok! I have a flashVar variable that is coming into Flash, its URL encoded but I have already decoded it. My problem is I want the set of variables to be pushed into an array.
Let's say the variables are
"&text0=Enter Text...&size0=18&font0=Arial&color0=0&rotation0=0&y0=360&x0=640&text1=Enter
Text...&size1=18&font1=Arial&color1=0&rotation1=0&y1=360&x1=640"
and so on...
What I want is the variables to go into an array like
myArray[0].text = Enter Text...
myArray[0].size = 18]
myArray[0].font = Arial
myArray[0].color = 0
myArray[0].rotation = 0
myArray[0].y = 360
myArray[0].x = 640
myArray[1].text = ...........
.............................
.............................
myArray[n].text = ...........
I think there must be some way to do this. Most probably I'm thinking regular expression, but I'm pretty bad at regular expression. Please some help would be very very appreciated.
Thank You!
You don't have to decode your query string, just use the URLVariables object - it will do all the decoding for you. Then iterate over its dynamic properties to create your array. Use a RegExp to find the index numbers at the end of your variable keys:
function parseURLVariables( query:String ) : Array {
var vars:URLVariables = new URLVariables (query);
var arr:Array = [];
for (var key : String in vars) {
var splitIndex : int = key.search(/[0-9]+$/);
var name:String = key.substr (0,splitIndex);
var indexNumber:int = parseInt ( key.substr(splitIndex));
arr[indexNumber] ||= {};
arr[indexNumber][name] = vars[key];
}
return arr;
}
Since your query string starts with a an ampersand, you might have to use parseURLVariables ( myString.substr(1)), otherwise the URLVariables object will throw an error, complaining that the query string is not valid (it has to be url encoded, and start with a variable key).
you may use split method of string to something like this;
var astrKeyValue: Array = url.Split( "&" );
in this way each value in astrKeyValue is string keyvalue ( for example font1=Arial )
after than you may split each item with "=" and will get pair key and value ( for key - font1 and for value - arial)
so this code maybe will work for you
var str = "text0=Enter Text...&size0=18&font0=Arial&color0=0&rotation0=0&y0=360&x0=640&text1=Enter Text...&size1=18&font1=Arial&color1=0&rotation1=0&y1=360&x1=640"
var a : Array = str.split( "&" );
var newArr: Array = new Array()
for each ( var str1 in a )
{
var t: Array = str1.split( "=" );
newArr[ t[0] ] = t[1];
}
trace( newArr.text0 ) // -> Enter Text...
Here is a solution for you from me,
//your string data should be like this, there should be a seperate seperator (i've used pipe sign |) for each element which will be converted to an object and then pushed to the array
var strData:String = "text=Enter Text...&size=18&font=Arial&color=0&rotation=0&y=360&x=640|text=Enter Text...&size=18&font=Arial&color=0&rotation=0&y=360&x=640";
var myArray:Array = new Array();
var _tmpArr:Array = strData.split("|");
//populating the array
for(var i:int=0;i<_tmpArr.length;i++)
{
myArray.push(strToObj(_tmpArr[i]));
}
trace(myArray.length);
// coverts chunk of string to object with all key and value in it
function strToObj(str:String):Object
{
var obj:Object = new Object();
var tmpArr:Array = str.split('&');
for (var i:int = 0; i < tmpArr.length; i++)
{
var _arr:Array = String(tmpArr[i]).split('=');
var key:String = String(_arr[0]);
var val:String = String(_arr[1]);
obj[key] = val;
trace(key+" = "+val);
}
trace("----");
return obj;
}