find all lines that begin with `console` in notepad++ - find

How do I find all lines that begin with console in notepad++?
there can be zero to any number of spaces or tabs before the word console
suppose i have a file as follows:
'createdRow': function (row, data, index) {
console.log("data is: "); console.log(data);
fields=Object.keys(data)
console.log("fields is: "); console.log(fields);
noOfFields=fields.length
console.log("noOfFields is: "); console.log(noOfFields);
var highlightVal = 80;
var highlightClassName = 'highlight';
var counterIndexCount = 4;
for (var i=1; i <= counterIndexCount; i++) {
if (parseInt(data['counter'+ i].substring(0,2), 10) >= highlightVal) {
$('td', row).eq(i).addClass(highlightClassName);
} else {
$('td', row).eq(i).removeClass(highlightClassName);
}
}
I thought I might have to do something like \n console using the Extended option in the bottom left of the find search. But could not get it to work.
for my reference:
similar q asked here

Do a regex (regular expression) search for this:
^( |\t)*console
The ^ matches the start of the line; ( |\t)* matches any number of tabs or spaces; and console, of course, matches the text you're looking for.
If you want to match the whole line, add .* at the end:
^( |\t)*console.*

Type Ctrl+H
Then in the search window:
Find what: ^\s*console\b
then click on Find All in Current Document
You'll find the lines in the find result window.
^ : Begining of line
\s* : 0 or more any kind of space character
console : literally 'console'
\b : word boundary to make sure that is not matching 'consolefoobar'

Related

How to search roman numerals in string with dart language?

I'm new to flutter. i have a string which have some roman numbers that indicate steps.. so i want to arrange that steps with new line and don't know how to do it. i tried string.replaceAll() but cannot get it since there are many roman number and some of then are the same such as i and ii. for example i have this string..
String text = 'some text here i) some step 1 ii) some step 2 iii) some step 3. some text after step blabla '
I want the output to have '\n' infront of the roman number which will arrange the output
some text here
i) some step 1
ii) some step 2
iii) some step 3
some text after step blabla
is there something i can use to detect the numeral numbers and add '\n' infront of it in the string or is there some other way.
There is probably a simpler way to do this with some sort of regex that I don't know about, but something like this should work.
String text = 'Your String'
List<String> words = text.split(' ');
String result = '';
for(var word in words){
if(word.endsWith(')')){
result += word + '\n';
}else{
result += word
}
}
//result now contains the desired string
Tricky to know when "some text after step blabla" should have line breaks in front because I don't know what to look for... That you would have to specify more closely.
Using the Numerus package to check for valid Roman Numeral.
Have this a go:
String text = 'some text here i) some step 1 ii) some step 2 iii) some step 3. ao) invalid roman numberal. some textafter';
RegExp regexp = new RegExp(r"((\w+)\))");
final stringWithLinebreaks = text.replaceAllMapped(regexp, (match) {
return match.group(2).isValidRomanNumeral()
? '\n${match.group(1)}'
: '${match.group(1)}';
});
print(stringWithLinebreaks);
That will print out:
some text here
i) some step 1
ii) some step 2
iii) some step 3. ao) invalid roman numberal. some textafter
You could of course make it better in several ways. Such as converting the roman numeral to int value using toRomanNumeralValue(), then sorting the steps accordingly if they are in the incorrect order in the text string. You could also make the RegExp more precise in several ways. For instance replacing \w with [iIvVxXlLcCdDmM] and so on..
i've found the answer from javascript and modify some of it... this is my answer... but i managed to search roman number from 1 to 10 only.. but its ok since the step never exceed more than 10
String formatText(String text) {
RegExp regExp = new RegExp(r'(?:viii?|i(?:ii?|[vx])?|vi?|x)\)');
String value = text.replaceAllMapped(regExp, (match) => "\n${match.group(0)}");
return value;
}

VSCode: Extension: folding section based on first blank line found or to the start of the next similar section

How can I make a VSCode extension folding strategy based on the first blank line following a starting folding marker?
## Some section --|
Any text... | (this should fold)
...more text. --|
(blank line)
## Another section (next fold...)
I've tried lots of regex in the language-configuration.json.
"folding": {
"markers": {
"start": "^##",
"end": "^\\s*$"
} },
If I change things to test with something other than a blank (or whitespace) line as the end delimiter it works. Can't use the next start marker to mark the end of the last or it includes it in the fold (I tried look ahead regex, but I think the regex are applied line by line and the matches can't span lines?)
It's similar to the folding needed for Markdown which VSCode handles well (don't know if that's using a more complex method like https://code.visualstudio.com/api/references/vscode-api#FoldingRangeProvider).
Maybe something in the fixes for [folding] should not fold white space after function has something to do with it.
What I learned: 1. the begin and end regex are applied line by line. 2. tmLanguage start/end regex will work on blank lines, but currently language-configuration folding doesn't seem to work on blank lines.
And since blank lines are in this case a hack for ending at the next begin section:
To solve the problem of folding a section to the next similar section I used the FoldingRangeProvider.
disposable = vscode.languages.registerFoldingRangeProvider('myExt', {
provideFoldingRanges(document, context, token) {
//console.log('folding range invoked'); // comes here on every character edit
let sectionStart = 0, FR = [], re = /^## /; // regex to detect start of region
for (let i = 0; i < document.lineCount; i++) {
if (re.test(document.lineAt(i).text)) {
if (sectionStart > 0) {
FR.push(new vscode.FoldingRange(sectionStart, i - 1, vscode.FoldingRangeKind.Region));
}
sectionStart = i;
}
}
if (sectionStart > 0) { FR.push(new vscode.FoldingRange(sectionStart, document.lineCount - 1, vscode.FoldingRangeKind.Region)); }
return FR;
}
});
Set "editor.foldingStrategy": "auto". You can make it more sophisticated to preserve white space between sections.

haxe: get line number and line position from haxe.macro.Position

In haxe macro for every expression we can get it's position in form of http://api.haxe.org/haxe/macro/Position.html :
{
file:String, // filename - relative to source path
min:Int, // position of first character in file
max:Int // position of last character in file
}
I want to get line number and position in line for min and max variables.
I definitely can do this by opening the file
FileSystem.absolutePath(Context.resolvePath(posInfo.file));
and calculating line number, but haxe already does this, it's much better to get this info from compiler. Is it possible?
In the current versions of Haxe you can use PositionTools.toLocation
class Macro {
public static macro function log(args:Array<Expr>):Expr {
var loc = PositionTools.toLocation(Context.currentPos());
var locStr = loc.file + ":" + loc.range.start.line;
args.unshift(macro $v{locStr});
return macro SomeExtern.logFunc($a{args});
}
}
to have Macro.log("hi!") translate into SomeExtern.logFunc("Main:5", "hi!")
I know a few projects do that manually (like checkstyle)
Load the file content, find the carriage returns (\n, \r or \n\r) mark the character position for each new line, lookup your pos.min against those positions
I guess it might be more problematic if you have multibyte characters in the file ...
In haxe 4 PositionTools.toLocation function was added.

lex program to count the Number of Words

I made the following lex program to count the Number of words in a Textfile. A 'Word' for me is any string that starts with an alphabet and is followed by 0 or more occurrence of alphabets/numbers/_ .
%{
int words;
%}
%%
[a-zA-Z][a-zA-Z0-9_]* {words++; printf("%s %d\n",yytext,words);}
. ;
%%
int main(int argc, char* argv[])
{
if(argc == 2)
{
yyin = fopen(argv[1], "r");
yylex();
printf("No. of Words : %d\n",words);
fclose(yyin);
}
else
printf("Invalid No. of Arguments\n");
return 0;
}
The Problem is that for the following Textfile, I am getting the No. of Words : 13. I tried printing the yytext and it shows that it is taking 'manav' from '9manav' as a word even though it doesnot match my definition of a word.
I also tried including [0-9][a-zA-Z0-9_]* ; within my code but still shows the same output. I want to know why is this happening and possible ways to avoid it.
Textfile : -
the quick brown fox jumps right over the lazy dog cout for
9manav
-99-7-5 32 69 99 +1
First, the manav is perfectly matching your definition of word. The 9 in front of it is matched by the . rule. Remember, that white space is not special in lex.
You had the right idea by adding another rule [0-9][a-zA-Z0-9_]* ; but since the ruleset is ambiguous (there are several ways to match the input) order of the rules matters. It's a while I worked with lex but I think putting the new rule before the word rule should work.

Algorithm to get a list of all words that are anagrams of all substrings (scrabble)?

Eg if input string is helloworld I want the output to be like:
do
he
we
low
hell
hold
roll
well
word
hello
lower
world
...
all the way up to the longest word that is an anagram of a substring of helloworld. Like in Scrabble for example.
The input string can be any length, but rarely more than 16 chars.
I've done a search and come up with structures like a trie, but I am still unsure of how to actually do this.
The structure used to hold your dictionary of valid entries will have a huge impact on efficiency. Organize it as a tree, root being the singular zero letter "word", the empty string. Each child of root is a single first letter of a possible word, children of those being the second letter of a possible word, etc., with each node marked as to whether it actually forms a word or not.
Your tester function will be recursive. It starts with zero letters, finds from the tree of valid entries that "" isn't a word but it does have children, so you call your tester recursively with your start word (of no letters) appended with each available remaining letter from your input string (which is all of them at that point). Check each one-letter entry in tree, if valid make note; if children, re-call tester function appending each of remaining available letters, and so on.
So for example, if your input string is "helloworld", you're going to first call your recursive tester function with "", passing the remaining available letters "helloworld" as a 2nd parameter. Function sees that "" isn't a word, but child "h" does exist. So it calls itself with "h", and "elloworld". Function sees that "h" isn't a word, but child "e" exists. So it calls itself with "he" and "lloworld". Function sees that "e" is marked, so "he" is a word, take note. Further, child "l" exists, so next call is "hel" with "loworld". It will next find "hell", then "hello", then will have to back out and probably next find "hollow", before backing all the way out to the empty string again and then starting with "e" words next.
I couldn't resist my own implementation. It creates a dictionary by sorting all the letters alphabetically, and mapping them to the words that can be created from them. This is an O(n) start-up operation that eliminates the need to find all permutations. You could implement the dictionary as a trie in another language to attain faster speedups.
The "getAnagrams" command is also an O(n) operation which searches each word in the dictionary to see if it is a subset of the search. Doing getAnagrams("radiotelegraphically")" (a 20 letter word) took approximately 1 second on my laptop, and returned 1496 anagrams.
# Using the 38617 word dictionary at
# http://www.cs.umd.edu/class/fall2008/cmsc433/p5/Usr.Dict.Words.txt
# Usage: getAnagrams("helloworld")
def containsLetters(subword, word):
wordlen = len(word)
subwordlen = len(subword)
if subwordlen > wordlen:
return False
word = list(word)
for c in subword:
try:
index = word.index(c)
except ValueError:
return False
word.pop(index)
return True
def getAnagrams(word):
output = []
for key in mydict.iterkeys():
if containsLetters(key, word):
output.extend(mydict[key])
output.sort(key=len)
return output
f = open("dict.txt")
wordlist = f.readlines()
f.close()
mydict = {}
for word in wordlist:
word = word.rstrip()
temp = list(word)
temp.sort()
letters = ''.join(temp)
if letters in mydict:
mydict[letters].append(word)
else:
mydict[letters] = [word]
An example run:
>>> getAnagrams("helloworld")
>>> ['do', 'he', 'we', 're', 'oh', 'or', 'row', 'hew', 'her', 'hoe', 'woo', 'red', 'dew', 'led', 'doe', 'ode', 'low', 'owl', 'rod', 'old', 'how', 'who', 'rho', 'ore', 'roe', 'owe', 'woe', 'hero', 'wood', 'door', 'odor', 'hold', 'well', 'owed', 'dell', 'dole', 'lewd', 'weld', 'doer', 'redo', 'rode', 'howl', 'hole', 'hell', 'drew', 'word', 'roll', 'wore', 'wool','herd', 'held', 'lore', 'role', 'lord', 'doll', 'hood', 'whore', 'rowed', 'wooed', 'whorl', 'world', 'older', 'dowel', 'horde', 'droll', 'drool', 'dwell', 'holed', 'lower', 'hello', 'wooer', 'rodeo', 'whole', 'hollow', 'howler', 'rolled', 'howled', 'holder', 'hollowed']
The data structure you want is called a Directed Acyclic Word Graph (dawg), and it is described by Andrew Appel and Guy Jacobsen in their paper "The World's Fastest Scrabble Program" which unfortunately they have chosen not to make available free online. An ACM membership or a university library will get it for you.
I have implemented this data structure in at least two languages---it is simple, easy to implement, and very, very fast.
A simple-minded approach is to generate all the "substrings" and, for each of them, check whether it's an element of the set of acceptable words. E.g., in Python 2.6:
import itertools
import urllib
def words():
f = urllib.urlopen(
'http://www.cs.umd.edu/class/fall2008/cmsc433/p5/Usr.Dict.Words.txt')
allwords = set(w[:-1] for w in f)
f.close()
return allwords
def substrings(s):
for i in range(2, len(s)+1):
for p in itertools.permutations(s, i):
yield ''.join(p)
def main():
w = words()
print '%d words' % len(w)
ss = set(substrings('weep'))
print '%d substrings' % len(ss)
good = ss & w
print '%d good ones' % len(good)
sgood = sorted(good, key=lambda w:(len(w), w))
for aword in sgood:
print aword
main()
will emit:
38617 words
31 substrings
5 good ones
we
ewe
pew
wee
weep
Of course, as other responses pointed out, organizing your data purposefully can greatly speed-up your runtime -- although the best data organization for a fast anagram finder could well be different... but that will largely depend on the nature of your dictionary of allowed words (a few tens of thousands, like here -- or millions?). Hash-maps and "signatures" (based on sorting the letters in each word) should be considered, as well as tries &c.
What you want is an implementation of a power set.
Also look at Eric Lipparts blog, he blogged about this very thing a little while back
EDIT:
Here is an implementation I wrote of getting the powerset from a given string...
private IEnumerable<string> GetPowerSet(string letters)
{
char[] letterArray = letters.ToCharArray();
for (int i = 0; i < Math.Pow(2.0, letterArray.Length); i++)
{
StringBuilder sb = new StringBuilder();
for (int j = 0; j < letterArray.Length; j++)
{
int pos = Convert.ToInt32(Math.Pow(2.0, j));
if ((pos & i) == pos)
{
sb.Append(letterArray[j]);
}
}
yield return new string(sb.ToString().ToCharArray().OrderBy(c => c).ToArray());
}
}
This function gives me the powersets of chars that make up the passed in string, I then can use these as keys into a dictionary of anagrams...
Dictionary<string,IEnumerable<string>>
I created my dictionary of anagrams like so... (there are probably more efficient ways, but this was simple and plenty quick enough with the scrabble tournament word list)
wordlist = (from s in fileText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
let k = new string(s.ToCharArray().OrderBy(c => c).ToArray())
group s by k).ToDictionary(o => o.Key, sl => sl.Select(a => a));
Like Tim J, Eric Lippert's blog posts where the first thing to come to my mind. I wanted to add that he wrote a follow-up about ways to improve the performance of his first attempt.
A nasality talisman for the sultana analyst
Santalic tailfans, part two
I believe the Ruby code in the answers to this question will also solve your problem.
I've been playing a lot of Wordfeud on my phone recently and was curious if I could come up with some code to give me a list of possible words. The following code takes your availble source letters (* for a wildcards) and an array with a master list of allowable words (TWL, SOWPODS, etc) and generates a list of matches. It does this by trying to build each word in the master list from your source letters.
I found this topic after writing my code, and it's definitely not as efficient as John Pirie's method or the DAWG algorithm, but it's still pretty quick.
public IList<string> Matches(string sourceLetters, string [] wordList)
{
sourceLetters = sourceLetters.ToUpper();
IList<string> matches = new List<string>();
foreach (string word in wordList)
{
if (WordCanBeBuiltFromSourceLetters(word, sourceLetters))
matches.Add(word);
}
return matches;
}
public bool WordCanBeBuiltFromSourceLetters(string targetWord, string sourceLetters)
{
string builtWord = "";
foreach (char letter in targetWord)
{
int pos = sourceLetters.IndexOf(letter);
if (pos >= 0)
{
builtWord += letter;
sourceLetters = sourceLetters.Remove(pos, 1);
continue;
}
// check for wildcard
pos = sourceLetters.IndexOf("*");
if (pos >= 0)
{
builtWord += letter;
sourceLetters = sourceLetters.Remove(pos, 1);
}
}
return string.Equals(builtWord, targetWord);
}