Normally, switch case in expect looks like this:
switch -- $count \
1 {
set type byte
} 2 {
set type word
} big {
set type array
} default {
puts "$count is not a valid type"
}
I need to use regex operators such as | or & - how can I do that?
The below example does not work with expect code :
switch -- $variable \
("a"|"b"|"c") {
do something
}
("a"|"b"|"c") represents a or b or c, but it does not seem to work.
How do I use such statements in switch or may be an and statement?
Use the -regexp option for the command, and brace the expression the Tcl way. Also, you can use braces around all the switches so you don't have to use line continuations.
switch -regexp -- $variable {
{a|b|c} {
do something
}
{^[def].*(?:g|h|i)} {
do a different thing
}
default {
do something else
}
}
http://tcl.tk/man/tcl8.5/TclCmd/switch.htm
http://tcl.tk/man/tcl8.5/TclCmd/re_syntax.htm
Related
Just a basic question related to python regex.
My code is this
void main void()
{
abc
{
tune
}
{
wao
}
}
i want to replace the abc ,tune and wao with different values like abc=u, tune=p and wao=m.
I am unable to select these two sub brackets of code in my regex.
The Regex which i am using is \{([^}]+)\}.
I want to write a code which can substitute these values in such a way that first all sub brackets were substituted i.e (tune=p and wao=m) then main brackets are substituted (abc=u).
If you do want to make use of regex, the following will work for the given example:
import re
code = """void main void()
{
abc
{
tune
}
{
wao
}
}
"""
code = re.sub(r"({\s*)[^{\s]+(\s*{)", r"\1u\2", code)
code = re.sub(r"({\s*)[^{\s]+(\s*})(?=\s*{)", r"\1p\2", code)
code = re.sub(r"({\s*)[^{\s]+(\s*})(?=\s*})", r"\1m\2", code)
print(code)
Output:
void main void()
{
u
{
p
}
{
m
}
}
But in general cases it is recommended to do a stateful parsing as #wim suggests.
I'm trying to make a program that outputs the most used character in a file.
Why does the compiler give me an error when I try this:
for (char i = 97 ; i <=122 ; i ++) {
switch (x) {
case i :
break;
}
}
This code uses a switch to get the most used characters. The error is :
'i' cannot appear in a constant-expression
case labels need to be compile time constants, and you are trying to use variable i, so you get the rather descriptive error message.
If you need to test against variables, the direct replacement is if-else if-...-else ladder. Though your simple case has no "else" part, Additionally, break breaks out of the switch, so you can't use it to break out of a loop then (direct replacement would be to use goto but it's far better to rethink your logic in almost all cases).
So write your code like this:
for (char i = 97 ; i <=122 ; i ++) {
if (x == i) {
break; // did you mean to break the loop?
}
}
I need a regular expression to extract the following text block functions only.
Example:
// Comment 1. function example1() { return 1; } // Comment 2 function example2() { if (a < b) { a++ } } // Comment 3 function example3() { while (1) { i++; } } /* Comment 4 */ function example4() { i = 4; for (i = 1; i < 10; i++) { i++; } return i; }
Take into account that no line breaks. It is a single block of code.
I have tried using the following regular expression:
Expression:
function\s[a-z|A-Z|0-9_]+()\s?{(?:.+)\s}
But there is a problem, place the .+ , take me all characters to the end of the text block.
Thanks in advance guys for the help you can give me.
In PCRE (PHP, R, Delphi), you can achieve this with recursion:
function\s[a-zA-Z0-9_]+\(\)(\s?{(?>[^{}]|(?1))*})
See demo.
In Ryby, just use \g<1> instead of (?1):
function\s[a-zA-Z0-9_]+\(\)(\s?{(?>[^{}]|(\g<1>))*})
In .NET, you can match them using balanced groups:
function\s[a-zA-Z0-9_]+\(\)\s*{((?<sq>{)|(?<-sq>})|[^{}]*)+}
See demo 2
In other languages, there is no recursion, and you need to use a workaround by adding nested levels "manually". In your examples, you have 2 levels.
Thus, in Python, it will look like:
function\s[a-zA-Z0-9_]+\(\)(?:\s?{(?:[^{}]*(?:\s*{[^{}]*}[^{}]*)*})*)
See Python demo (also works in JavaScript
In Java, you will need to escape {:
function\s[a-zA-Z0-9_]+\(\)(?:\s?\{(?:[^\{}]*(?:\s*\{[^{}]*}[^{}]*)*})*)
I'm trying to find a way to simplify the comparison cases of booleans. Currently, there are only three (as shown below), but I'm about to add a 4th option and this is getting very tedious.
bracketFirstIndex = message.indexOf('[');
mentionFirstIndex = message.indexOf('#');
urlFirstIndex = message.indexOf(urlStarter);
bool startsWithBracket = (bracketFirstIndex != -1);
bool startsWithAtSymbol = (mentionFirstIndex != -1);
bool startsWithUrl = (urlFirstIndex != -1);
if (!startsWithBracket)
{
if (!startsWithAtSymbol)
{
if (!startsWithUrl)
{
// No brackets, mentions, or urls. Send message as normal
cursor.insertText(message);
break;
}
else
{
// There's a URL, lets begin!
index = urlFirstIndex;
}
}
else
{
if (!startsWithUrl)
{
// There's an # symbol, lets begin!
index = mentionFirstIndex;
}
else
{
// There's both an # symbol and URL, pick the first one... lets begin!
index = std::min(urlFirstIndex, mentionFirstIndex);
}
}
}
else
{
if (!startsWithAtSymbol)
{
// There's a [, look down!
index = bracketFirstIndex;
}
else
{
// There's both a [ and #, pick the first one... look down!
index = std::min(bracketFirstIndex, mentionFirstIndex);
}
if (startsWithUrl)
{
// If there's a URL, pick the first one... then lets begin!
// Otherwise, just "lets begin!"
index = std::min(index, urlFirstIndex);
}
}
Is there a better/more simpler way to compare several boolean values, or am I stuck in this format and I should just attempt to squeeze in the 4th option in the appropriate locations?
Some type of text processing are fairly common, and for those, you should strongly consider using an existing library. For example, if the text you are processing is using the markdown syntax, consider using an existing library to parse the markdown into a structured format for you to interpret.
If this is completely custom parsing, then there are a few options:
For very simple text processing (like a single string expected to
be in one of a few formats or containing a piece of subtext in an expected format), use regular expressions. In C++, the RE2 library provides very powerful support for matching and extracting usign regexes.
For more complicated text processing, such as data spanning many lines or having a wide variety of content / syntax, consider using an existing lexer and parser generator. Flex and Bison are common tools (used together) to auto-generate logic for parsing text according to a grammar.
You can, by hand, as you are doing now, write your own parsing logic.
If you go with the latter approach, there are a few ways to simplify things:
Separate the "lexing" (breaking up the input into tokens) and "parsing" (interpreting the series of tokens) into separate phases.
Define a "Token" class and a corresponding hierarchy representing the types of symbols that can appear within your grammar (like RawText, Keyword, AtMention, etc.)
Create one or more enums representing the states that your parsing logic can be in.
Implement your lexing and parsing logic as a state machine that transforms the state given the current state and the next token or letter. Building up a map from (state, token type) to next_state or from (state, token type) to handler_function can help you to simplify the structure.
Since you are switching only on the starting letter, use cases:
enum State { Start1, Start2, Start3, Start4};
State state;
if (startswithbracket) {
state = Start1;
} else {
.
.
.
}
switch (state) {
case Start1:
dosomething;
break;
case Start2:
.
.
.
}
More information about switch syntax and use cases can be found here.
I'm trying to make a switch case based on partial strings using Groovy's pattern matching. I've already got this working -
String s = "abc";
switch(s){
case { it =~ /b/ } :
//this works
break;
.....
}
But when I try to abstract out the closure I run into issues -
String s = "abc";
def partialMatch = {string, pattern -> string =~ /$pattern/}
switch(s){
case partialMatch(s, "b"):
//this doesn't work
break;
.....
}
It seems like the match is working, but the case still doesn't trigger for some reason. Why is that?
You'd need to put partialMatch in a Closure for it to be executed by the switch:
case {partialMatch(s, "b")}: