FAQ Database Discussion Community


Rascal pattern guards

pattern-matching,rascal
Does Rascal support pattern guards? I'm trying to order subexpressions on build: data Expr = and(Expr l, Expr r) | ... ; Expr and(l, r) | r < l = and(r, l); // fictional syntax for "r < l" guard If guards are unsupported, what's the best way to implement...

How to do pattern matching in Rx. Where + Select in a single operator?

f#,pattern-matching,system.reactive
Suppose I have this type: type T = int option and an observable of that type: let o : IObservable<T> = // create the observable I'm looking for a better way to express this: o.Where(function | None -> false | Some t -> true) .Select(function | Some t -> t)...

Find & count occurrences of certain words matching text/string/paragraph (most efficient way)

php,regex,algorithm,compare,pattern-matching
I have a Paragraph that I have to parse for different keywords. For example, Paragraph: "I want to make a change in the world. Want to make it a better place to live. Peace, Love and Harmony. It is all life is all about. We can make our world a...

Match and replace operation in data frame in R

r,replace,pattern-matching,match,vlookup
Let's say my dataset is like the following: John NA kaira carry John NA maya Sam maya leo paty leo tinker NA tinker fabo leo maya I have another dataset: John 1 carry 2 maya 3 leo 4 tinker 5 fabo 6 sam 7 paty 8 kaira 9 I want...

how to parse everything that comes after 'P' with java pattern matcher?

java,regex,pattern-matching
I have some data items of the form: blahblahblahP26 blahblahblahP82982 blahblahblahP0 blahblahblahP913 I know that the java pattern matcher is a bit different than normal regex. What I'd like to do is just grab everything that comes after the P. No more, no less. How to do that?...

Delete some lines from text using Linux command

linux,shell,sed,grep,pattern-matching
I know how to match text using regex patterns but not how to manipulate them. I have used grep to match and extract lines from a text file, but I want to remove those lines from the text. How can I achieve this without having to write a python or...

Scala tuple extraction in function declaration

scala,pattern-matching
Given for instance a Tuple2 of the form type Duple = (String,Int) this function errs to extract and label the duple's items in the arguments, def f( (s,n): Duple ): String = s*n However this works, def f( d: Duple ): String = { val (s,n) = d s*n }...

Does scala support one default clause for many pattern matching?

scala,pattern-matching
Consider a code below: val first = ... val second = ... val third = ... val fours = ... first match { case "someString" => second match { case s:String => third match { case MyEnum.A => //some logic case MyEnum.B => fours match { case Some(old:String) => //some...

How to match pattern 2.0.0.XXX in lua?

lua,pattern-matching,string-matching
How can I match the pattern 2.0.0.xxx in lua? I want a pattern which can match all such patterns. Example: If a = 2.0.0.100 and b=2.0.0.200 c= 2.1.0.122 d=2.0.1.122 only a and b should match the pattern...

Scala: elegant way to use require to validate multiple options?

scala,functional-programming,coding-style,pattern-matching,require
I have two solutions for this problem. I do not like both of them so I was wondering if there's a more elegant solution. import java.util.Date import scala.math.Ordered.orderingToOrdered // Solution # 1: case class A(startDate: Option[Date] = None, endDate: Option[Date] = None) { require(if (startDate.isEmpty && endDate.isEmpty) false else true,...

Matching positive integer with haskell

haskell,pattern-matching,ghc
Is it possible with pattern matching to match a range of values ? For example : the whole positive integers ? odd numbers ? a list of values ? ...

Find last occurrence of a string in a file from a specific location in that file

c++,regex,pattern-matching
I want to find the last occurrence of a string in a text file of initial size 5MB (might go up to 10MB max) from a fixed specific location (a delimiter) in the same file. I got through finding all occurrences but how to print the last/ final occurrence from...

Pattern match on Tuple2 of Success

scala,pattern-matching,type-erasure
I have 2 Futures of Try and i want to do something only if both of them successfully complete. Both the Futures are independent. So here is some code def a1: Future[Try[String]] = Future { Success("a1") } def a2: Future[Try[Int]] = Future { Success(2) } val r1 = for {...

Is there a way to search partial match in multivalue field in PostgreSQL?

arrays,postgresql,pattern-matching
I have a table quiet like this: CREATE TABLE myTable ( family text, names text[] ) I can search like this: SELECT family FROM myTable where names @> array['B0WP04']; But I would like to do: SELECT family FROM myTable where names @> array['%P0%']; Is this possible ?...

New line matcher “no match”

java,pattern-matching
I'm writing a java server and always read requests form the browser. For example, I have in browser http://localhost:8080/great and read this request like GET /great HTTP/1.1 Host: localhost:8080 Connection: keep-alive Cache-Control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36 OPR/29.0.1795.47 Accept-Encoding: gzip,...

Extracting text after “?” in R

r,pattern-matching,rstudio
I have a string x <- "Name of the Student? Michael Sneider" I want to extract "Michael Sneider" out of it. I have used: str_extract_all(x,"[a-z]+") str_extract_all(data,"\\?[a-z]+") But can't extract the name....

R Match character vectors

r,pattern-matching,string-matching
var1 is a character vector var1 <- c("tax evasion", "all taxes", "payment") and var2 is another character vector var2 <- c("bill", "income tax", "sales taxes") Want to compare var1 and var2 and extract the terms which has a partial word match, for example, the desired answer in this case will...

Recursive function in haskell

algorithm,haskell,recursion,pattern-matching,towers-of-hanoi
I am trying to solve some issues with programming in haskell. I am having this three types and the Hanoi-algorithm: type Position = Int type Move = (Position,Position) type Towers = ([Int],[Int],[Int]) hanoi 1 i j = [(i,j)] hanoi n i j = hanoi n' i otherT ++ [(i,j)] ++...

Scala Illegal Start of Simple Expression: Option Type and Ellipsis

scala,pattern-matching,option,options,ellipsis
New to Scala and just began the scala.Option Cheat Sheet. However, this code is throwing an error in the sbt console. def option[A, X](o: Option[A])(none: => X, some: => A => X): X = ... The error is error: illegal start of simple expression the up-arrow points to the ellipsis....

awk to exclude range patterns but include the start pattern

bash,awk,pattern-matching
Say we got an example file: 11 12 ss dd gg 32 ss dd gg So i want to remove the block which meet the pattern ss gg, but i want to keep the start pattern ss The out put should be 11 12 ss 32 ss Using this code...

populate a java hashmap with data from file

java,regex,hashmap,pattern-matching
I have the following data structure: "properties": { "P6": "head of government", "P7": "brother", "P9": "sister", "P10": "video", "P14": "highway marker", "P15": "road map", "P16": "highway system", "P17": "country", "P18": "image", "P19": "place of birth", "P20": "place of death", "P21": "sex or gender", ... I'd like to read this in...

find string including quotation marks using grep

grep,pattern-matching,quotes
How can I find a string which includes quotation marks with grep? I tried a backslash to escape but this doesn't work. For example search for the string "localStorage['api']". I tried: grep -r "localStorage['api']" /path grep -r "localStorage[\'api\']" /path ...

Matching on part of a binary in a method signature

pattern-matching,elixir
I'm reading a binary file, and within it there is a structure where the first byte of data indicates the type of data following it. I'm trying to handle this via pattern matching, and am having trouble. I've tried a few ways I figured may work, none of which do....

Pattern matching with finite automata

c++,regex,algorithm,pattern-matching,finite-automata
Recently I was reading the famous Algorithm design book CLRS(Cormen, Leiserson, Rivest, Stain, 3-rd edition). And between the classical KMP and Rabin - Karp algorithm there is a part about string matching with finite automata. So the algorithm creates the automata according to the pattern and starts processing on the...

Find location of a pattern of bits in a binary array in matlab

arrays,matlab,binary,pattern-matching
I have an array of binary data with long stretches of ones and zeros and I want to find the indices of when it changes. a = [ 1 1 1 1 1 0 0 0 0 0 0 1 1] I want to search for [1 0] and [0...

Need help in pattern matching IN Perl

regex,perl,pattern-matching
Hoe to do the pattern match of "Iface Name: bnx2i.00:17:a4:77:14:2f" exactly? There should not be spaces or new lines before and after.

Preventing move semantics during pattern matching

pattern-matching,rust,move
I have a silly example here, just to demonstrate an issue I'm running into with another library and pattern matching. struct Person { name: String, age: i32, choice: Choices } #[derive(Debug)] enum Choices { Good, Neutral, Evil } fn find(p: Person) { match (p.choice, p.age) { (Choices::Good, a) if a...

Regular Expression to find CVE Matches

regex,pattern-matching
I am pretty new to the concept of regex and so I am hoping an expert user can help me craft the right expression to find all the matches in a string. I have a string that represents a lot of support information in it for vulnerabilities data. In that...

How can I filter filename patterns in Powershell?

powershell,pattern-matching
I need to do something similar to Unix's ls | grep 'my[rR]egexp?' in Powershell. The similar expression ls | Select-String -Pattern 'my[rR]egexp?' seems to go through contents of the listed files, rather than simply filtering the filenames themselves. The Select-String documentation hasn't been of much help either. ...

Lua string.match utf - asking for spanish character - getting half portuguese

utf-8,lua,pattern-matching
Hi the following code in Lua: letters = "Vocéá" print(string.match("¡Você","["..letters.."]+")) returns: �Voc� if I replace é with regular e and get rid of á then I get "Voc". seems that á interferes with ¡, and é with ê. Could it be that they share a byte in common? I am...

Pattern matching over an AST struct in the compiler

pattern-matching,rust
So I am trying to pattern match on a struct. This particular struct is made-up of a number of enums, which contain pointers to enums, or at its most basic level, a vector un-signed 8-bytes. I would like to work with the vector, however would like to know if it...

find and replace strings in files in a particular directory

regex,sed,find,pattern-matching
I have a pattern that I need to replace in my .hpp, .h, .cpp files in multiple directories. I have read Find and replace a particular term in multiple files question for guidance. I am also using this tutorial but I am not able achieve what I intend to do....

Match string in XText regardless of upper/lower case

java,eclipse,pattern-matching,dsl,xtext
I want to create a rule in XText that matches to a string, but does not care in what case the string is. For example, I want it to match against both "DUCK", "DucK" and "duck". Is there a more simple way of doing it than covering all cases, like:...

How to handle below pattern matching in Perl

regex,perl,pattern-matching,special-characters
How to do the below mentioned pattern match? Below input is in an array: @array=("gs : asti:34:234", "gs : asti:344:543:wet"); I used foreach loop so that I split them and I'm pushing them into an array. Help me in resolving the below issue. foreach(@array) { if($_ =~ /gs/ig) { my...

Scala string pattern matching for html tagged contents extraction

string,scala,pattern-matching,scala-string
Given a HTML page fetched from val html = io.Source.fromURL("http://example.org/aPage.html").mkString() how to extract the contents wrapped within a given tag ? To illustrate this consider for instance this HTML fragment and tag <textarea>, val html = "<p>Marginalia</p> <textarea rows="3" cols="10">Contents of interest"</textarea <p>More marginalia</p>" how to obtain "Contents of interest"...

Scala pattern matching extractors right associativity

scala,pattern-matching
I'm currently playing around with Scala's pattern matching. What I know so far is, that an extractor named like an operator gets left associative and an extractor named like a method or type is right associative. My current approach looks something like this: object Foo { def unapply(tokens: Seq[String]): Option[(Seq[String],...

Regular expression to extract the word from the string ${VALUE(word_to_be_extracted)} in java

java,regex,pattern-matching
What is the best regex to extract the word inside that string? Pattern pattern = Pattern.compile("pattern here"); Matcher matcher = pattern.matcher(${VALUE(word_to_be_extracted)}); while(matcher.find()) { System.out.println(matcher.group()); } ...

Extracting the text from a Log using Regular Expression

python,regex,text,pattern-matching
I have a log message like this (12/12/2013 03:12:21 PM) 06:21:22.234 - 5463723 : ##Some Message## i need to write a regular expression to extract Some Message from above log record. How can i write a regular expression to extract the required words out. Note: I am using python language...

Pattern Matching Array of Bytes

scala,pattern-matching,scala-collections
This fails to compile: Array[Byte](...) match { case Array(0xFE.toByte, 0xFF.toByte, tail @ _* ) => tail } I can, however, compile this: val FE = 0xFE.toByte val FF = 0xFF.toByte bytes match { Array( FE, FF, tail @ _* ) => tail } Why does the first case fail to...

How to perl regex match in R in the grepl function?

r,function,pattern-matching,pcre,grepl
I have a function in R which uses the grepl command as follows: function(x) grepl('\bx\b',res$label, perl=T) This doesn't seem to work - the 'x' input is a character type string (a sentence), and i'd like to create word boundaries around the 'x' as I match, as I don't want the...

Comparing files line by line using a simple pattern match

regex,perl,pattern-matching,string-matching
I have two files: in the first file each line has some labels associated with it; the second file contains the labels which fall under certain categories. File1 - labelled lines: I have never had an issue. L_102 ----- L_127 I travel overseas and offer a lot of services that...

R - how to find exact pattern when listing files

r,pattern-matching
I have a number of files from which I would like to find only the ones that match an exact pattern. When I run: mods=c('GISS-E2-H','GISS-E2-R','GISS-E2-R-CC') files <- list.files(idir, pattern=mods[1]) I got the results: > files [1] "clt_Amon_GISS-E2-H-CC_historical_r1i1p1_185001-190012.nc" [2] "clt_Amon_GISS-E2-H-CC_historical_r1i1p1_190101-195012.nc" [3] "clt_Amon_GISS-E2-H-CC_historical_r1i1p1_195101-201012.nc" [4] "clt_Amon_GISS-E2-H_historical_r1i1p1_185001-190012.nc" [5] "clt_Amon_GISS-E2-H_historical_r1i1p1_190101-195012.nc"...

Can I use the pattern matching operator ~= to match an enum value to an enum type with an associated variable? [duplicate]

swift,enums,pattern-matching
This question already has an answer here: How to test equality of Swift enums with associated values 5 answers I would like to compare an enum value to an enum type without using switch. The following code, for example, works using the ~= operator: enum MyEnum { case A,...

match expression falling through?

pattern-matching,rust
Here is some contrived but simple pattern matching example (demo): fn main() { let x = 'a'; match x { 'a'...'b' if false => { println!("one"); }, 'a' => { println!("two"); }, 'a'...'b' => { println!("three"); }, _ => panic!("what?") } } When I run it, I get three as...

Python: pattern matching(?)

python,pattern-matching
I am a beginner in Python programming and I have a question about constructing a code. Let's say I have the following data: 150 z Brazil 160 a Toys R Us I want to code such that if we see the pattern bbb \t (one digit or character not a)...

Postgresql : Pattern matching of values starting with “IR”

sql,postgresql,pattern-matching
If I have table contents that looks like this : id | value ------------ 1 |CT 6510 2 |IR 52 3 |IRAB 4 |IR AB 5 |IR52 I need to get only those rows with contents starting with "IR" and then a number, (the spaces ignored). It means I should...

Can `match` in Racket have patterns with variables from an outer scope?

scope,scheme,pattern-matching,racket
Consider the following example: #lang racket (match '(cat . doge) [`(,a . ,b) (match b [a #t] [_ #f])] [_ "Not a pair"]) This is what I might write if I wanted to match pairs where the head and tail are the same. This doesn't work though because the second...

Can macros expand to a combination of patterns?

macros,pattern-matching,rust
As of Rust 1.0, there is no way to group multiple patterns into one binding: // It does not compile match x as char { b @ ('A' | 'Z') => println!("A or Z: {}", b), _ => println!("Try again") } // Correct version match x as char { b...

Extract series of observations from dataframe for complete sets of data

r,loops,data.frame,pattern-matching,subset
I have a data frame of values composed of 5 variables (class in brackets) 1) DateTime (as.POSIXct), 2) ID (character), 3) Sensor 1 (numeric), 4) Sensor 2 (numeric), 5) Sensor 3 (numeric) This data was collected from 5 tagged fish. Each fish has one tag with 3 sensors on it,...

F# less than operator in pattern matching

f#,pattern-matching
For some reason the less than operator in this pattern match will not work. It's the only error I have and it's driving me insane. I'm probably missing something really obvious but all help is appreciated. let CheckAccount account = match account with | {Balance < 10.00} -> Console.WriteLine("Balance is...

Read string variables into variables [closed]

python,pattern-matching
I have three keywords %vel, %note, %blah that I want to parse from strings into integers: s = "%vel=127, %note=64, %blah=13" # should give { 'vel': 127, 'note': 64, 'blah': 13} # or vel = 127 // note = 64 // blah = 13 or s = "%blah=5,%note=44" # should...

R character match and rank

r,grep,pattern-matching,string-matching
I have a character vector var1 <- c("pine tree", "dense forest", "red fruits", "green fruits", "clean water", "pine") and a list var2 <- list(c("tall tree", "fruits", "star"), c("tree tall", "pine tree", "tree pine", "black forest", "water"), c("apple", "orange", "grapes")) I want to match words in var1 with elements in var2,...

Substitute only in the matched part of a Perl pattern

regex,perl,pattern-matching
How can I substitute only in matched pattern and put it back in same variable using Perl? For example: my $str = "a.b.AA pat1 BB hgf AA pat1 BB jkl CC pat1 don't change pat1"; I want to match pat1 between AA and BB and replace it with Original string...

One line boolean pattern matching in Scala

scala,pattern-matching
Is there a way to write this code in a more elegant way in Scala? Basically I have the following algebraic data type: trait Exp case class Atom(i: Int) extends Exp case class Add(l: Exp, r: Exp) extends Exp and I want to check if a given variable matches a...

How to define map fusion in the Pure language?

functional-programming,pattern-matching
I'm experimenting with the Pure language based on term rewriting. I want to define "map fusion" using an equation, like this: > map f (map g list) = map (f . succ . g) list; (The succ is there to verify that the rule kicks in.) However, it doesn't seem...

Performance difference between pattern matching and if-else

performance,pattern-matching,ocaml
Why can OCaml generate efficient machine code for pattern matching and not for if-else tests? I was reading Real World OCaml and I came across this section where they compared the performance of pattern matching to the performance of if-else tests. It turned out that pattern matching in their example...

Efficicient way for Java pattern Matching

java,string,pattern-matching
What is the best and the fastest way to check if a string matches something like:"AB+SPACE+NUMBER+ANYTHING eg: "AB 1234 DEFG" I am looking for the most efficient way, as it is going to compare thousands of transaction per minute.

Match a minimum number of concurrent lines in multiline regular expression

regex,pattern-matching
I am looking for a pattern that will allow me to identify a range of text in a document that consists of a list of words. Use this text as an example. property subject recipe newsletter news match reply bulletin joke annual greeting accepted puzzle march meeting din order alert...

Regex to validate that first letter of every word is capital in angular js

regex,angularjs,validation,pattern-matching,ng-pattern
I am using angularjs. I want to use validation for my name field. I am a beginner in regex expressions. I want that the first letter of every word should be capital. For E.g Naveen Kumar should be valid and Naveen kumar is invalid. I am using ng-pattern to validate...

VBA Like Operator

vba,pattern-matching,outlook-vba,sql-like
I want to monitor our public e-mail folder for specific new mails to arrive and then use MsgBox to create a pop-up Window. Everything is set up and works prett well apart from the matching part using the Like Operator. I want to match the following string in the subject...

Python data frame column string extraction efficient way?

python,pandas,pattern-matching,dataframes
I have a data frame df with column ID in the following pattern. What I want is to return a string column with the number after the dash sign. For the example below, I need 01,01,02. I used the command below and it failed. Since it is a very large...

Break data into array elements based of two or more spaces

php,regex,file,pattern-matching
I'm trying to parse a tabbed text file which has on a single line multiple parts of data, the only way to differentiate between each part of data is that the parts are separated by gaps of two or more spaces or tabs. I've found tons of answers on stack...

F# Function Matching

.net,f#,functional-programming,pattern-matching
Is there a way in F# to define a function that gives the sum of all the natural numbers up to the integer parameter provided, without using a match construct. In other words, why is the following code wrong? let Sum 0 = 0 let Sum n = n +...

How to remove comment HTML element in a String in iOS

html,ios,swift,pattern-matching,nsregularexpression
This is the last part of my String: </div> </noscript><!-- A g3.js-t oldalanként egyszer, a </body> zárótag előtt kell meghívni --> <script type="text/javascript" charset="utf-8" src="//ad.adverticum.net/g3.js"></script> <div id="autosuggest"><ul></ul></div> </body> </html> And this is how I want to remove the comment element, but it does not work: var regex = NSRegularExpression(pattern: "<!--[^<]*-->",...

RegEx Pattern - Time Format

javascript,pattern-matching
I've a problem with a RegEx pattern and it's maddening me ;-) Can anybody help me, please? My RegEx Pattern: /(\d+)?:?(\d+):(\d+)/ Time-Strings: 2:03, 24:35, 2:43:36 Output: Array [ "2:03", undefined, "2", "03" ] // correct Array [ "24:35", "2", "4", "35" ] // should be: [ "24:35", undefined, "24", "35"...

FSharp pattern that matches List type

list,f#,pattern-matching
I want to match the object obj1 of type "obj" according to its actual type. The problem is that the type check pattern for list type (the second one in the example below) does not match F# lists. let obj1 = [1;2;3] :> obj match obj1 with | :? System.Array...

Patttern matching within collection

scala,pattern-matching
I would like to look for a specific pattern inside a Seq. I tried to use at the same time :+ and +: operators but it doesn't seem to work even though it compiles, for now I have to rely on 'dropwhile' operation first and then pattern match on the...

Python: Reggular Expressions filtering for Self Learning program

python,regex,pattern-matching,artificial-intelligence
I am making a program that has a small way of self learning, but now I want to get "information" from the output like: >>>#ff0000 is the hexcode for the color red I want to filter with reggular expressions that the user filled this sentence is the hexcode for the...

How can I match this pattern in haskell

haskell,pattern-matching
I've got data LNode(TypedL(2.72489e12,"http://www.w3.org/2001/XMLSchema#double")) I want an anonymous function to match from this to 2.72489e12 myfunc (LNode(TypedL(c, d))) = c gives Constructor `TypedL' should have 2 arguments, but has been given 1. Is my syntax with this function wrong?...

How to avoid (unnecessary?) repetitive use of axioms in Agda?

types,pattern-matching,agda
Is there a method to programmatically construct (sub)proofs in Agda? Because some proofs are very similar and it's better to simplify them... but i don't know how to do this. Consider for example the following code {- At first we reaname Set to 𝓤 (as in Universe) -} 𝓤 =...

Patterns (preferably java) find floor space in sq ft

java,regex,pattern-matching
I have the following data that needs parsing. The pattern could be (1) approx 1,000 sq ft (2)c. 500sqft (3) 2,100 sq ft This is my code to find a digit but I need the above... in java Pattern regex = Pattern.compile("\\d[\\d,\\.]+"); Matcher finder = regex.matcher(price); if(finder.find()){ try { String...

Ruby Regex Group Replacement

ruby,regex,pattern-matching,gsub
I am trying to perform regular expression matching and replacement on the same line in Ruby. I have some libraries that manipulate strings in Ruby and add special formatting characters to it. The formatting can be applied in any order. However, if I would like to change the string formatting,...

Matching complex inheritance-y thing

pattern-matching,rust
I have a kind of complex inheritance-y thing I'm trying to match in Rust: struct Entity { pub kind: EntityKind, } pub enum EntityKind { Player(PlayerData), } pub struct PlayerData { pub name: String, } How do I match it with the pattern matching stuff, for instance: // pretend theres...

Pattern matching on variant without deconstructing in Haskell

haskell,pattern-matching
In the following code, the function disp is defined by de-constructing Sum b c and then immediately reconstructing it. The problem is that I don't need b and c, only the fact that it is of type Sum. data Expr = Name String | Sum Expr Expr deriving(Show) disp (Sum...

Scala unapplySeq extractor syntax

scala,pattern-matching,scala-2.11
I (inadvertently) came across a bit of pattern matching syntax I did not expect to compile and now cannot figure out. It appears related to unapplySeq. Note the case x List(_,_) part in this simple example: val xs = List(1, 2, 3) //> xs : List[Int] = List(1, 2, 3)...

Scala list pattern matching in value declaration

list,scala,pattern-matching,tuples
Assuming the following list of four tuples: > def getList = List( (1,2), (3,4), (5,6), (7,8) ) I want to parse it into three sections in new values declaration like this - the last tuple (l1,l2), the penultimate tuple (p1,p2) and the rest of the list rest. Moreover, I'd like...

Scala sum of all elements in the leaves of a tree using pattern matching

scala,tree,sum,pattern-matching,case-statement
I'm learning Scala by working the exercises from the book "Scala for the Impatient". One of the questions asks: /** * Q5: One can use lists to model trees that store values only in the leaves. For example, the list ((3, 8) 2 (5)) * describes the tree * ....

awk to compare two file by identifier & output in a specific format

awk,pattern-matching,gawk
I have 2 large files i need to compare all pipe delimited file 1 a||d||f||a 1||2||3||4 file 2 a||d||f||a 1||1||3||4 1||2||r||f Now I want to compare the files & print accordingly such as if any update found in file 2 will be printed as updated_value#oldvalue & any new line added...

Collapse similar case statements in Scala

scala,functional-programming,pattern-matching
Is there an elegant way to do something like the following example using just one case statement? foobar match { case Node(Leaf(key, value), parent, qux) => { // Do something with parent & qux } case Node(parent, Leaf(key, value), qux) => { // Do something with parent & qux (code...

Meaning of [email protected] in akka receive

scala,pattern-matching,akka,actor
I was surfing some code examples on akka and I found a particular example that I would like to be sure of the meaning: def receive: Receive = { case [email protected](x) => // do stuff case _ => //do stuff } Ping is a case class used for message in...

Any java based frameworks/tools to handle pattern matching and pattern filling

java,regex,pattern-matching
Edit Apparently people aren't actually reading this question. I realize I can do pattern matching with regex. Which is what my example code does, the main problem is the pattern filling and handling that nicely without having to split the regex up in to it's individual tokens and figuring out...

How to remove rows that match one of several regex patterns?

regex,unix,awk,sed,pattern-matching
I have a tab-delimited text file and wish to efficiently remove whole rows that fulfil either of the following criteria: values in the ALT column that are equal to . values in the NA00001 column and subsequent columns that have the same digit before and after either of the two...

R match whole words in phrases

r,string,grep,pattern-matching
I have a character vector var1 <- c("pine tree", "forest", "fruits", "water") and a list var2 <- list(c("tree", "house", "star"), c("house", "tree", "pine tree", "tree pine", "dense forest"), c("apple", "orange", "grapes")) I want to match words in var1 with words in var2, and extract the maximum matching element in var2....

match string inside quotes having at-least 1 uppercase char

java,regex,eclipse,pattern-matching
i have some string lines in my java files and trying to do an Eclipse Regex search but its not working. i want to highlight lines which have an Uppercase character in the string after RequestParam(value = so from below 3 lines, only middle one should match ie RequestParam(value =...

awk to print all colums formatted

awk,pattern-matching
I want to format below un-formatted inputs. I would like to print all the fields if the second column begins with "2". Actual file contains many columns. Is there any easiest way to print all columns instead of typing print $2,$3,$4,$5,...$n? Input.csv --------------------------- |Data statistics|Number of| |-------------------------| |Records passed |...

Swift 2 - Pattern matching in “if”

swift,if-statement,syntax,pattern-matching,swift2
Recently I've saw the WWDC 2015 keynote from Apple. I also looked at some documentation but I can't find a "pattern matching in if" section, how it was written on one of the slides which they have shown. (73min 00sec video from Apple Events) Do you know what's this refers...

Find a specific string from a line through all the file

c++,string,pattern-matching,fstream,ofstream
I have a file in which i want to search a specific string in a line then compare that string through the whole file which consists of 5000lines. All lines that match the string will be writen on another text file beneath each other. So far i have succeeded to...

Regex with a variable number of match groups

python,regex,pattern-matching
I would like to be able to write patterns to recognize filenames in a list: import re NOTES = ["c", "c#", "d", "d#", "e", "f", "f#", "g", "g#", "a", "a#", "b"] filelist1 = ["piano c3.wav", "piano c#3.wav", "piano d4.wav"] pattern1 = "piano %notename.wav" filelist2 = ["72__54.wav", "60__127.wav", "48__61.wav"] pattern2 =...

Optimize byte array simple pattern matching

java,pattern-matching,bytearray
For an excercisement i had to look for a certain byte pattern within an byte array, easy enough but i wonder if the code can be simplified or even be optimized: package anti_virus; import java.nio.file.Files; import java.nio.file.Paths; public class Main { public static void main(String[] args) throws Exception { byte[]...

last element of array matching scala

arrays,regex,scala,pattern-matching
Good afternoon! I'm using Scala and I want to match first three element of a list and the last one, no matter how much of them are in the list. val myList:List[List[Int]] = List(List(3,1,2,3,4),List(23,45,6,7,2),List(3,3,2,1,5,34,43,2),List(8,5,3,34,4,5,3,2),List(3,2,45,56)) def parse(lists: List[Int]): List[Int] = lists.toArray match{ case Array(item, site, buyer, _*, date) => List(item, site,...

Scala: pattern matching Option with case classes and code blocks

scala,pattern-matching
I'm starting to learn the great Scala language ang have a question about "deep" pattern matching I have a simple Request class: case class Request(method: String, path: String, version: String) {} And a function, that tries to match an request instance and build a corresponding response: def guessResponse(requestOrNone: Option[Request]): Response...

A more complex version of “How can I tell if a string repeats itself in Python?”

python,string,pattern-matching,bioinformatics
I was reading this post and I wonder if someone can find the way to catch repetitive motifs into a more complex string. For example, find all the repetitive motifs in string = 'AAACACGTACGTAATTCCGTGTGTCCCCTATACGTATACGTTT' Here the repetitive motifs: 'AAACACGTACGTAATTCCGTGTGTCCCCTATACGTATACGTTT' So, the output should be something like this: output = {'ACGT':...

How to search a particular string in a file using pattern matcher in java

java,regex,pattern-matching
I have the following paragraph java.net.SocketException: ***Connection reset*** at java.net.SocketInputStream.read(SocketInputStream.java:197) at jcifs.netbios.SessionServicePacket.readPacketType(SessionServicePacket.java:68) at jcifs.netbios.NbtSocket.connect(NbtSocket.java:107) at jcifs.netbios.NbtSocket.<init>(NbtSocket.java:68) at jcifs.smb.SmbTransport.ensureOpen(SmbTransport.java:275) at jcifs.smb.SmbTransport.send(SmbTransport.java:602) at jcifs.smb.SmbTransport.negotiate(SmbTransport.java:847) at...

Agda: Simulate Coq's rewrite tactic

pattern-matching,proof,agda,dependent-type
I have some experience using Coq and am now in the process of learning Agda. I'm working on a correctness proof of insertion sort and have reached a point where I would like to perform something similar to Coq's rewrite tactic. Currently, I have: open import Data.Nat open import Relation.Binary.PropositionalEquality...

R match two lists and find matching elements

r,list,pattern-matching,string-matching
I have two lists: lst1 <- list(c("environmental science", "environmental social science", "nature"), c("bodies of water", "erosion landforms", "valleys"), c("meteorological concepts", "climate", "environmental"), c("fireplaces", "metalworking", "industrial")) lst2 <- list(c("environmental social", "fragile", "ocean"), c("air", "water", "rain water"), c("day", "astronomy")) I want to retain the groupings of list elements, and match the elements...

option[Any] pattern matching in Scala

scala,pattern-matching
I've written the following code for finding the value corresponding to a key and returning it as Double. def getDouble (key: String, map: HashMap[String, _]) : Double = { if (map contains key) { val o = map get key o match { case Some(i: Int) => return i.asInstanceOf[Int].toDouble; case...

Splitting hairs whilst splitting strings

string,pattern-matching,idris
I tried to make a function in Idris like so: strSplit : String -> Maybe (Char, String) This would 'un-cons' the string into its first Char and the rest of the string, and return Nothing if it were empty. So I wrote this, which failed: strSplit x = case strM...

First word of binary string erlang

functional-programming,erlang,pattern-matching
I need to do something like this <<"Some text in binary">>, and it should return <<"Some">. How can i do it without split function, only by pattern matching and select/if cases with Erlang. Thank you.

Regular expression to replace a file name in the full path to file using C#

c#,.net,regex,replace,pattern-matching
I have a batch file(.bat) whose contents looks something like below cd C:\RunningDir\TestResults vstest.console.exe C:\Dir1\Dir2\ProductBin\TestBin\bin\Debug\BVTTests.orderedtest /Settings:C:\Dir1\Dir2\ProductBin\TestBin\bin\Debug\QuestCodedUI.testsettings /Logger:trx vstest.console.exe C:\Dir1\Dir2\ProductBin\TestBin\bin\Debug\Functional_Tests_1.orderedtest /Settings:C:\Dir1\Dir2\ProductBin\TestBin\bin\Debug\QuestCodedUI.testsettings /Logger:trx vstest.console.exe...

Collect results of multiple partial functions at single value?

scala,pattern-matching,partialfunction
Suppose I have some partial functions that may have overlapping domains: val funcs: Seq[PartialFunction[Any, Int]] = Vector( { case i: Int if i % 2 == 0 => i*2 } , { case i: Int if i % 2 == 1 => i*3 } , { case i: Int if...