Menu
  • HOME
  • TAGS

Read string variables into variables [closed]

python,pattern-matching

Really quick list comprehension example: s = "%blah=5, %note=44" print dict([item.split('=') for item in s.replace(' ','').replace('%', '').split(',')]) Edit: s = "%blah=5, %note=44" # existing dict old_dict_with_data = { ... } result = dict(map(lambda x: [x[0], int(x[1])], [item.split('=') for item in s.replace(' ', '').replace('%', '').split(',')])) old_dict_with_data.update(result) I'd suggest split this comprehension...

last element of array matching scala

arrays,regex,scala,pattern-matching

You do not need to convert lists to Arrays, because lists are designed for pattern matching. scala> myList match { case item :: site :: buyer :: tail if tail.nonEmpty => item :: site :: buyer :: List(tail.last) } res3: List[List[Int]] = List(List(3, 1, 2, 3, 4), List(23, 45, 6,...

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

c#,.net,regex,replace,pattern-matching

You don't even need a regular expression to do what you want: var path = @"C:\SystemSetup\Runner.bat"; var text = System.IO.File.ReadAllText(path); text = text.Replace("BVTTests.orderedtest", "SmokeTests.orderedtest"); text = text.Replace("Functional_Tests_1", "Functional_Tests_3"); System.IO.File.WriteAllText(path, text); Is there a specific reason you want to use Regex? Edit: You can find all occurences of your test files...

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

utf-8,lua,pattern-matching

Characters and bytes are two different things. Characters can be encoded in bytes in various ways, using different encodings. One possible encoding is UTF-8. Unfortunately Lua's string.match doesn't know almost anything about charactes and encodings, it only works with bytes. So your script is not looking for the "V", "c",...

Pattern matching with finite automata

c++,regex,algorithm,pattern-matching,finite-automata

Check the table (b). All the states you are talking about are marked as 0. So you go back to the beginning. In the image you would get a lot of edges back to 0 so they don't show them (for clarity).

Extracting the text from a Log using Regular Expression

python,regex,text,pattern-matching

You can use the following: (?<=##)[^#]*(?=##) See DEMO...

How to match pattern 2.0.0.XXX in lua?

lua,pattern-matching,string-matching

This pattern works: "2%.0%.0%.%d%d%d" ...

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

java,regex,pattern-matching

You can use Xeger to generate/fill strings based on patterns. Here an interesting example from its documentation: String regex = "[ab]{4,6}c"; Xeger generator = new Xeger(regex); String result = generator.generate(); assert result.matches(regex); For your case, you could use: String regex = "\\d{4}"; Xeger generator = new Xeger(regex); String result =...

R Match character vectors

r,pattern-matching,string-matching

May be you need lst1 <- strsplit(var1, ' ') lst2 <- strsplit(var2, ' ') indx1 <- sapply(lst1, function(x) any(grepl(paste(unlist(lst2), collapse="|"), x))) indx2 <- sapply(lst2, function(x) any(grepl(paste(unlist(lst1), collapse="|"), x))) c(var1[indx1], var2[indx2]) #[1] "tax evasion" "all taxes" "income tax" "sales taxes" If there are intersects between var1 and var2, wrap with with...

R match whole words in phrases

r,string,grep,pattern-matching

We create a pattern string ('pat') for the grepl , by first splitting the 'var1' by space '\\s+'. The output will be a list. We use sapply to loop over the list, use paste with collapse= '|', and then collapse the whole vector to a single string with another paste....

Scala Illegal Start of Simple Expression: Option Type and Ellipsis

scala,pattern-matching,option,options,ellipsis

... is not a valid Scala expression. If you want a function with an "unknown" implementation you can use ???: def option[A, X](o: Option[A])(none: => X, some: => A => X): X = ??? The goal of this function is apparently to take a function as parameter and to apply...

R character match and rank

r,grep,pattern-matching,string-matching

We can loop over 'var2' (sapply(var2,) , split the strings at white space (strsplit(x, ' ')), grep the output list elements as pattern for 'var1'. Check if there is any match, sum the logical vector and rank it. This can be used for reordering the 'var2' elements. indx <- rank(-sapply(var2,...

Extract series of observations from dataframe for complete sets of data

r,loops,data.frame,pattern-matching,subset

Your question boils down to searching for sequences of "ABC" within the sequences of the IDs: (matches <- gregexpr("ABC", paste(dat$ID, collapse=""))[[1]]) # [1] 8 # ... This indicates that the only match begins at row 8. You now know that the information for Sensor1 are at rows numbered matches, the...

Substitute only in the matched part of a Perl pattern

regex,perl,pattern-matching

Not very simple with one single regexp, so I used divide and conquer to compute the result. This is a small recursive function that is replacing a single '.' per group of ('\' ' ') The iteration ends when there is nothing to replace sub replace { my ($input) =...

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

python,string,pattern-matching,bioinformatics

you can use a recursion function as following : import re def finder(st,past_ind=0,l=[]): m=re.search(r'(.+)\1+',st) if m: i,j=m.span() sub=st[i:j] ind = (sub+sub).find(sub, 1) sub=sub[:ind] if len(sub)>1: l.append([sub,(i+past_ind+1,j+past_ind+1)]) past_ind+=j return finder(st[j:],past_ind) else: return l s='AAACACGTACGTAATTCCGTGTGTCCCCTATACGTATACGTTT' print finder(s) result: [['ACGT', (5, 13)], ['GT', (19, 25)], ['TATACG', (29, 41)]] answer to previous question for...

Pattern matching over an AST struct in the compiler

pattern-matching,rust

A few things are going awry here. ast::Lit is just a type alias of codemap::Spanned, not an enum or an enum variant. So you don't need to specify both, but you must specify either. ast::ExprLit is an enum tuple variant containing a P<Lit>. So you need to destructure the P...

Find a specific string from a line through all the file

c++,string,pattern-matching,fstream,ofstream

So I take it you need to group the input file lines based in some substring keys. The simplest way would be to populate in-memory line group collections as your read the file and then after processing the entire input flush the groups to the output file: #include <iostream> #include...

Meaning of [email protected] in akka receive

scala,pattern-matching,akka,actor

It is a Scala feature called variable binding. It binds the value being matched on to the variable. You can find more examples here Scala @ operator

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

From the documentation for Swift 1.2 "Enumeration case patterns appear only in switch statement case labels". So yes, you need to define your ~= operator (as from the answer pointed in the comments). In case you just need isA and isB you can implement them using switch combined with _....

Python data frame column string extraction efficient way?

python,pandas,pattern-matching,dataframes

Use vectorised str method split if you have a recent version of pandas: In [26]: df['val'].str.split('-').str[1] Out[26]: 0 01 1 01 2 02 dtype: object If the dash position was fixed then you could slice it In [28]: df['val'].str[8:] Out[28]: 0 01 1 01 2 02 Name: val, dtype: object...

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

awk,pattern-matching,gawk

I would say: awk 'BEGIN{FS=OFS="|"} FNR==NR {for (i=1;i<=NF;i+=2) a[FNR,i]=$i; next} {for (i=1; i<=NF; i+=2) if (a[FNR,i] && a[FNR,i]!=$i) $i=$i"#"a[FNR,i] }1' f1 f2 This stores the file1 in a matrix a[line number, column]. Then, it compares its values with its correspondence in file2. Note I am using the field separator |...

VBA Like Operator

vba,pattern-matching,outlook-vba,sql-like

Look for the exceptions, then compare with the wildcard: Select Case UCase$(Left$(subject, 3)) Case "RE:", "AW:": '// is reply Case Else If subject Like "*XXX*YYY*" Then MsgBox "Hello" End If End Select ...

match string inside quotes having at-least 1 uppercase char

java,regex,eclipse,pattern-matching

This should work in Eclipse search: RequestParam *\( *value *= *"[^"\nA-Z]*[A-Z][^"\n]*" RegEx Demo Make sure case sensitive and regex checkboxes are checked in Eclipse search....

Match a minimum number of concurrent lines in multiline regular expression

regex,pattern-matching

You were close. You need to group the expression inside parentheses so that the quantifier will apply to the whole expression, not just the immediately preceding character. You also need to put the line break itself into the regexp as well. /(^\w+$\n){20,}/ Depending on the language you're using, you may...

Pattern Matching Array of Bytes

scala,pattern-matching,scala-collections

Matching as currently implemented in Scala does not allow you to generate expressions inside your match statement: you must either have an expression or a match, but not both. So, if you assign the values before you get into the match, all you have is a stable identifier, and the...

Python: pattern matching(?)

python,pattern-matching

Q. how do I code such that I select one digit or character that is not a? A. '[^a]' The regular expression syntax is documented here....

Patttern matching within collection

scala,pattern-matching

This will never work in that definition as you can not wildcard any subsequence except tail in result of unapplySeq. But let me suggest a workaround. Lets define this helper: object Span { class Spanner[T](pred: T => Boolean) { def unapply(seq: Seq[T]) = for { idx <- Some(seq.indexWhere(pred)) if idx...

Splitting hairs whilst splitting strings

string,pattern-matching,idris

There are two problems here. Firstly, in the 'case' block, the argument is strM rather than strM x as it is in the 'with' block, so you're inspecting different things. There's a more interesting problem though, which is that if you try fixing the first one: strSplit : String ->...

Swift 2 - Pattern matching in “if”

swift,if-statement,syntax,pattern-matching,swift2

All it really means is that if statements now support pattern matching like switch statements already have. For example, the following is now a valid way of using if/else if/else statements to "switch" over the cases of an enum. enum TestEnum { case One case Two case Three } let...

Regex with a variable number of match groups

python,regex,pattern-matching

I think what you're looking for are named capturing groups. Try this: pattern1 = pattern1.replace("%midinote", r"(?P<midinote>\d+)").replace("%velocity", r"(?P<velocity>\d+)").replace("%notename", r"(?P<notename>[A-Ga-g]#?[0-9])") for fname in filelist1: m = re.match(pattern1, fname) if m: info = m.groupdict() midinote = int(info.get('midinote',0)) velocity = int(info.get('velocity',0)) notename = info.get('notename', 'c') notenametomidi = NOTES.index(notename[:-1].lower()) + (int(notename[-1])+2) * 12 print fname,...

match expression falling through?

pattern-matching,rust

Looking at the LLVM IR in Debug, it is already flawed, so this is definitely a bug in rustc; we'll use the curated IR below to check what's going on. So, %x is assigned 'a' (97 in ASCII), and %10 is assigned the result of x >= 'a' and x...

Collect results of multiple partial functions at single value?

scala,pattern-matching,partialfunction

Partial functions have a lift method that is Some(res) if the PF is defined and None if not defined. Also with the use of flatMap we can essentially ignore the Nones and grab only the Some values. funcs.flatMap { func => func.lift(num) } Or compressed if you enjoy that sort...

Recursive function in haskell

algorithm,haskell,recursion,pattern-matching,towers-of-hanoi

I'm not sure exactly how your hanoi solution works, but I think this answers your question: all_moves :: ([Move], Towers) -> Towers all_moves ([], (xs, ys, zs)) = (xs, ys, zs) all_moves movetowers = all_moves (move movetowers) Hopefully you can see why this works - we keep doing a move...

Pattern matching on variant without deconstructing in Haskell

haskell,pattern-matching

disp (Sum (Name a) [email protected](Sum _ _)) = a ++ ":" ++ disp s @ allows multiple matches for the same thing...

Agda: Simulate Coq's rewrite tactic

pattern-matching,proof,agda,dependent-type

You can use the Agda keyword rewrite to apply a propositional equivalence on your goal: insertCorrect : ∀ {n} -> ∀ x l -> sorted n l -> sorted (n ⊓ x) (insert x l) insertCorrect {n} x nil p with intDec n x insertCorrect {n} x nil p |...

Can macros expand to a combination of patterns?

macros,pattern-matching,rust

A macro is able to expand to things like patterns, expressions and items, but not everything; specifically, macros expand to complete AST nodes, but what you’re dealing with here is not a complete AST node. Each branch of a match expression can have one or more patterns, separated by pipes,...

Collapse similar case statements in Scala

scala,functional-programming,pattern-matching

You can use a custom extractor to abstract the matching part away from the logic part: object Leafed { def unapply(tree: Tree) = tree match { case Node(Leaf(_, _), parent, qux) => Some((parent, qux)) case Node(parent, Leaf(_, _), qux) => Some((parent, qux)) case _ => None } } And then...

How to remove comment HTML element in a String in iOS

html,ios,swift,pattern-matching,nsregularexpression

You can try using a slightly different regex: var regex = NSRegularExpression(pattern: "<!--[\\s\\S]*-->", options: NSRegularExpressionOptions.CaseInsensitive, error: nil)! ...

find and replace strings in files in a particular directory

regex,sed,find,pattern-matching

You can use the sed expression: sed 's/throw some::lengthy::exception();/throw CreateException(some::lengthy::exception());/g' And add it into a find command to check .h, .cpp and .hpp files (idea coming from List files with certain extensions with ls and grep): find . -iregex '.*\.\(h\|cpp\|hpp\)' All together: find . -iregex '.*\.\(h\|cpp\|hpp\)' -exec sed -i.bak 's/throw...

Scala unapplySeq extractor syntax

scala,pattern-matching,scala-2.11

The equivalent non-infix version is: xs match { case List(x, _, _) => "yes" case _ => "no" } Scala specification says: An infix operation pattern p;op;q is a shorthand for the constructor or extractor pattern op(p,q). The precedence and associativity of operators in patterns is the same as in...

Ruby Regex Group Replacement

ruby,regex,pattern-matching,gsub

You can use the following regex with back-reference \\1 in the replacement: reg = /(\\e\[(?:[0-9]{1,2}|[3,9][0-8])m)+Text/ mystring = "\\e[1mHello there\\e[34m\\e[40mText\\e[0m\\e[0m\\e[22m" puts mystring.gsub(reg, '\\1New Text') mystring = "\\e[1mHello there\\e[44m\\e[34m\\e[40mText\\e[0m\\e[0m\\e[22m" puts mystring.gsub(reg, '\\1New Text') Output of the IDEONE demo: \e[1mHello there\e[40mNew Text\e[0m\e[0m\e[22m \e[1mHello there\e[40mNew Text\e[0m\e[0m\e[22m Mind that your input has backslash \ that...

Scala string pattern matching for html tagged contents extraction

string,scala,pattern-matching,scala-string

There are two easy ways to do this: Scala XML Add the Scala XML dependency to your project: libraryDependencies += "org.scala-lang.modules" %% "scala-xml" % "1.0.3" Now you can parse your HTML code and select all textarea tags. import scala.xml.XML val htmlXml = XML.loadString(html) val textareaContents = (htmlXml \\ "textarea").text If...

Scala tuple extraction in function declaration

scala,pattern-matching

Start with a regular 2 arg function: scala> val f: (String, Int) => String = (a, b) => a * b f: (String, Int) => String = <function2> convert it to single arg function that accepts tuples: scala> val tf = f tupled tf: ((String, Int)) => String = <function1>...

Rascal pattern guards

pattern-matching,rascal

Just to simplify things I've used int as the type for l and r at first. What you want to do is something like the following: rascal>data Expr = and(int l, int r); ok rascal>Expr and(int l, int r) = and(r,l) when r < l; Expr (int, int): rascalfunction() rascal>and(5,6);...

option[Any] pattern matching in Scala

scala,pattern-matching

Some(int) matches any Some, and declares a variable named int of type Any from the contents of the Option. int is just an identifier here, not a type. So for example Some("String") would be matched by it, and would throw an exception when you tried to return it as an...

Scala list pattern matching in value declaration

list,scala,pattern-matching,tuples

You could use the :+ matcher object: val rest :+ ((p1, p2)) :+ ((l1, l2)) = getList It's the part of standard library since scala 2.10 For previous version you redefine it yourself using source ...

FSharp pattern that matches List type

list,f#,pattern-matching

Daniel Fabian has already explained the problem in his answer. One way to implement his solution is with an Active Pattern: let (|IsList|_|) (candidate : obj) = let t = candidate.GetType() if t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<list<_>> then Some (candidate :?> System.Collections.IEnumerable) else None You can now change the match...

R - how to find exact pattern when listing files

r,pattern-matching

Your solution works, the first three files also have the pattern GISS-E2-H. To get only the last three, you can do as suggested by @G.Grothendieck and add the _ to mods: mods=c('GISS-E2-H_','GISS-E2-R','GISS-E2-R-CC') Now to test your solution I'll create the files: allfiles <- c("clt_Amon_GISS-E2-H-CC_historical_r1i1p1_185001-190012.nc", "clt_Amon_GISS-E2-H-CC_historical_r1i1p1_190101-195012.nc", "clt_Amon_GISS-E2-H-CC_historical_r1i1p1_195101-201012.nc", "clt_Amon_GISS-E2-H_historical_r1i1p1_185001-190012.nc",...

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

r,function,pattern-matching,pcre,grepl

You just need to properly escape the slash in your regex ff<-function(x) grepl('\\bx\\b',x, perl=T) ff(c("axa","a x a", "xa", "ax","x")) # [1] FALSE TRUE FALSE FALSE TRUE ...

Scala pattern matching extractors right associativity

scala,pattern-matching

You need to end your class' name with an :. From the Scala Specifications (Infix Operations, 6.12.3) : The associativity of an operator is determined by the operator’s last character. Operators ending in a colon ‘:’ are right-associative. All other operators are left-associative. This way: scala> object `Foo:` { def...

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

f#,pattern-matching,system.reactive

Can't you use Observable.choose ? something like this : let o1 : IObservable<int option> = // ... let o2 = Observable.choose id o1 If you have a type that is not an option, say: type TwoSubcases<'a,'b> = | Case1 of 'a | Case2 of 'b and a partial active pattern:...

Matching complex inheritance-y thing

pattern-matching,rust

A solution while keeping your design with newtypes (learn more about newtypes): struct Entity { pub kind: EntityKind, } pub enum EntityKind { Player(PlayerData), Weapon(WeaponData), } pub struct PlayerData { pub name: String, } pub struct WeaponData { pub damage_per_shot: i32, } fn f(e: EntityKind) { match e { EntityKind::Player(player_data)...

Efficicient way for Java pattern Matching

java,string,pattern-matching

Use string.matches function which uses regex for string matching. string.matches("AB \\d+.*"); ^ ^ ^ ^ | | | |_ Anything AB | Num | space If you want space after number, then use "AB \\d+ .+" ...

find string including quotation marks using grep

grep,pattern-matching,quotes

Your escaping is OK. The problem lies in the [], that grep understands as regular expressions. Thus, you need to somehow tell it to treat the string as literal. For this we have -F: grep -F "localStorage['api']" file Test $ cat a hello localStorage['api'] and blabla bye $ grep -F...

Postgresql : Pattern matching of values starting with “IR”

sql,postgresql,pattern-matching

You can use the operator ~, which performs a regular expression matching. I.e: SELECT * from public.record where value ~ '^IR ?\d'; Add a asterisk to perform a case insensitive matching. SELECT * from public.record where value ~* '^ir ?\d'; The symbols mean: ^: begin of the string ?: the...

Pattern match on Tuple2 of Success

scala,pattern-matching,type-erasure

You can pattern match on tuple content: r1.map { case (_: Success[String], _: Success[Int]) => println("success") case _ => println("failure") } This way it overcomes type erasure by calling tuple's unapply method, getting tuple elements and then checking their types. And tuple elements do have their runtime types intact as...

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

java,regex,pattern-matching

Connection reset.*?\\b([^ .]+\\.xls)\\b You can use this regex.Grab the group 1 or capture 1.See demo. https://regex101.com/r/bN8dL3/3...

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

regex,unix,awk,sed,pattern-matching

Your example doesn't appear to include any lines that meet the "values in the ALT column that are equal to ." criterion, or lines that don't meet the second criterion (except the header line). So I added some lines of my own to your example for testing; I hope I've...

How to handle below pattern matching in Perl

regex,perl,pattern-matching,special-characters

You can do it in this way, split strings in only two parts: use strict; use warnings; my @array=('gs : asti:34:234', 'gs : asti:344:543:wet'); foreach(@array) { if($_ =~ m/gs/ig) { my @arr2 = split(":", $_, 2); $arr2[1] =~ s/^\s+//; #to remove the white-space push(my @y,$arr2[1]); print "@y\n"; } } Output:...

Python: Reggular Expressions filtering for Self Learning program

python,regex,pattern-matching,artificial-intelligence

You can read about regular expressions in Python in the standard library documentation. Here, I'm using named groups to store the matched value into a dictionary structure with a key that you choose. >>> import re >>> s = '#ff0000 is the hexcode for the color red' >>> m =...

F# Function Matching

.net,f#,functional-programming,pattern-matching

If you specifically want the recursive form without using match, just use a regular conditional: let rec Sum n = if n = 0 then 0 else n + Sum (n-1) The idiomatic way to emulate Haskell would be: let rec Sum = function | 0 -> 0 | n...

Need help in pattern matching IN Perl

regex,perl,pattern-matching

my $if = "Iface Name: bnx2i.00:17:a4:77:14:2f"; if ($if =~ /^Iface Name: ([a-f0-9]+\.(?:[a-f0-9]{2}:){5}[a-f0-9]{2})\z/) { print $1; } ...

awk to print all colums formatted

awk,pattern-matching

$ awk 'gsub(/\|/,",") && gsub(/^,|,$/,"") && /^2/' file 200965 ,18604165309338 ,18604165309387 ,2012 ,6100202749 ,AAA2778202 201163 ,10740000822407 ,10740000822606 ,2012 ,6100202749 ,AAA2778202 201232 ,18604177741067 ,18604177741366 ,2012 ,6100202749 ,AAA2778202 201295 ,18604221522337 ,18604221523836 ,2012 ,6100202749 ,AAA2778202 201480 ,18604113309952 ,18604113310131 ,2012 ,6100202749 ,AAA2778202 201781 ,18604199150436 ,18604199150835 ,2012 ,6100202749 ,AAA2778202 201480 ,6001400030046472 ,6001400030046771 ,2012 ,6100202520...

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

c++,regex,pattern-matching

Assigning your found text to a variable at each iteration will overwrite the variable content and printing it after the loop has ended would print only the last occurence: Something like this should do : #include <iostream> #include <string> #include <fstream> using namespace std; int main() { ifstream file; string...

Match and replace operation in data frame in R

r,replace,pattern-matching,match,vlookup

Could also do df1[] <- match(unlist(df1), df2$V1) # V1 V2 V3 # 1 1 NA 9 # 2 2 1 NA # 3 3 NA 3 # 4 4 8 4 # 5 5 NA 5 # 6 6 4 3 If the numbers in df2 are not always in...

awk to exclude range patterns but include the start pattern

bash,awk,pattern-matching

I would use a printing flag like this: $ awk '!flag; /ss/ {flag=1} /gg/ {flag=0}' file 11 12 ss 32 ss This uses a similar logic as How to select lines between two marker patterns which may occur multiple times with awk/sed, moving the flag in a way that makes...

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

arrays,matlab,binary,pattern-matching

Something like this should do the job: b = diff(a); % (assuming 'a' is a vector) oneFromZero = find(b == 1) + 1; % vector of indices of a '1' preceded by a '0' zeroFromOne = find(b == -1) + 1; % vector of indices of a '0' preceded by...

One line boolean pattern matching in Scala

scala,pattern-matching

You can use a PartialFunction and its isDefinedAt method: type MatchExp = PartialFunction[Exp, Unit] // alias val isOnePlusTwo: MatchExp = { case Add(Atom(1), Atom(2)) => } if (isOnePlusTwo.isDefinedAt(x)) println("match") A match expression produces either a Function or a PartialFunction, depending on the expected type. The type alias is only for...

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

scope,scheme,pattern-matching,racket

Use ==: (match '(cat . doge) [`(,a . ,b) (match b [(== a) #t] [_ #f])] [_ "Not a pair"]) Due to the placement in the docs, == is easy to overlook....

Break data into array elements based of two or more spaces

php,regex,file,pattern-matching

You need to modify your preg_split a bit. Check this out:- <?php $string ='DER V3,0,0,3323 Xkisjd 2014 02 25 05:23 PGM / RUN BY / DATE'; echo "<pre/>";print_r(preg_split("/\s\s+/",$string)); ?> Output:- http://prntscr.com/796wd7 If you want space will replace with - then do like this:- $data = preg_replace("/\s\s+/", "-", $string); echo $data;...

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

java,regex,pattern-matching

/\$\{VALUE\((.*)\)\}/ The first capture group will be your word...

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

arrays,postgresql,pattern-matching

You can use the parray_gin extension https://github.com/theirix/parray_gin This extension is said to work only up to 9.2 but I just installed and tested it on 9.3 and it works well. Here is how to install it on ubuntu-like systems :) # install postgresql extension network client and postgresql extension build...

R match two lists and find matching elements

r,list,pattern-matching,string-matching

We can try a nested loop. In the function f1match, we loop over the first list (sapply(list1, function(x)), split each element (strsplit(x, ' ')), loop over the output and split each element of list2 as before, check whether any element in split list element of list2 is in list1, check...

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

scala,functional-programming,coding-style,pattern-matching,require

Here is how I would write it: import java.util.Date case class MyTest(startDate: Option[Date] = None, endDate: Option[Date] = None) { require(startDate.isDefined || endDate.isDefined, "Either startDate or endDate must be defined") require(!(startDate.isDefined && endDate.isDefined) || (startDate.get.before(endDate.get)), s"startDate: ${startDate.get} must be less than endDate:${endDate.get}") } object Test extends App { // Gives...

F# less than operator in pattern matching

f#,pattern-matching

You can use pattern matching to extract the balance value, bind it to a new name and then compare the values using the when clause: let CheckAccount account = match account with | {Balance = b} when b < 10.00 -> Console.WriteLine("Balance is Low") | {Balance = b} when b...

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

types,pattern-matching,agda

You can programmatically generate proofs using Agda's reflection capability. Here's an example of your problem solved with a reusable tactic. I threw this together for this question, so I'm not promising that it's the most robust tactic. It should give you a sense of how to tackle problems like this...

Comparing files line by line using a simple pattern match

regex,perl,pattern-matching,string-matching

This combines your two scripts into one. It reads through the $inputfile file handle that is pointing at "INPUTFILE.txt"looking for matches based on either a regular expression ($regexp) or the existence of a search key in the %patterns hash. Since the match is simple, the regular expression we use is...

Performance difference between pattern matching and if-else

performance,pattern-matching,ocaml

match and if has different semantics: match is parallel, if is strictly sequential. If you have expression: match expr with | A -> e1 | B -> e2 | C -> e3 | ... Then it may compare branches in any order. In the example, I provided, it may compile...

Regular Expression to find CVE Matches

regex,pattern-matching

Generally you should always include your previous efforts in your question, what exactly you expect to match, etc. But since I am aware of the format and this is an easy one... CVE-\d{4}-\d{4,7} This matches first CVE- then a 4-digit number for the year identifier and then a 4 to...

Match string in XText regardless of upper/lower case

java,eclipse,pattern-matching,dsl,xtext

There is a flag that you can configure in the mwe2 workflow. Replace the XtextAntlrGeneratorFragment by the org.eclipse.xtext.generator.parser.antlr.ex.rt.AntlrGeneratorFragment and pass options = { ignoreCase = true }. Same for the XtextAntlrUiGeneratorFragment and the org.eclipse.xtext.generator.parser.antlr.ex.ca.ContentAssistParserGeneratorFragment

New line matcher “no match”

java,pattern-matching

The pattern should probably be Pattern.compile("^GET (.*) HTTP/1\\.1$.*", Pattern.MULTILINE | Pattern.DOTALL) Some of the errors in your pattern: As mentioned in the comment by @VGR, :* shouldn't be there, but since * is used, it means zero or more occurrences. And zero occurrences it is in your case. [\\n\\r] which,...

First word of binary string erlang

functional-programming,erlang,pattern-matching

Although Attic's approach is correct, there is a straightforward solution (including trimming of leading spaces): first_word_bin(Bin) -> first_word_bin(ltrim(Bin), <<>>). first_word_bin(<<>>, Acc) -> Acc; first_word_bin(<<$\s, _/binary>>, Acc) -> Acc; first_word_bin(<<X, Bin/binary>>, Acc) -> first_word_bin(Bin, <<Acc/binary, X>>). ltrim(<<$\s, Bin/binary>>) -> ltrim(Bin); ltrim(Bin) -> Bin. ...

Scala: pattern matching Option with case classes and code blocks

scala,pattern-matching

For the first part of your question, you can name the value you match against with @ : scala> case class A(i: Int) defined class A scala> Option(A(1)) match { | case None => A(0) | case Some(a @ A(_)) => a | } res0: A = A(1) From the...

Matching on part of a binary in a method signature

pattern-matching,elixir

Each unbound variable in a binary pattern matches one byte by default. If you want to match an arbitrary length rest, you need to use the binary modifier. defmodule Test do def build(<<0x11, rest :: binary>>) do "11!" end def build(<<0x12, rest :: binary>>) do "12!" end def build(<<0x13, rest...

How can I filter filename patterns in Powershell?

powershell,pattern-matching

Very simple: ls | where Name -match 'myregex' There are other options, though: (ls) -match 'myregex' Or, depending on how complex your regex is, you could maybe also solve it with a simple wildcard match: ls wild[ck]ard*.txt which is faster than above options. And if you can get it into...

Optimize byte array simple pattern matching

java,pattern-matching,bytearray

Yes, it can be simplified/optimized: You could use the KMP algorithm (first 14 bytes). This algorithm runs in O(payload.length + virus.length) for arbitrary payload instead of O(payload.length * virus.length). (Your code is working more efficiently than O(payload.length * virus.length) for only one reason: 0x56 occurs only as the first element...

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

php,regex,algorithm,compare,pattern-matching

As @CasimiretHippolyte commented, regex is the better means as word boundaries can be used. Further caseless matching is possible using the i flag. Use with preg_match_all return value: Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred. The pattern for matching one...

RegEx Pattern - Time Format

javascript,pattern-matching

I believe you just need a non-capture group surrounding your optional first digits and colon: (?:(\d+)?:)?(\d+):(\d+) Here is an example with it returning the results you wanted: http://www.regexr.com/3b4m2...

Extracting text after “?” in R

r,pattern-matching,rstudio

str_match is more helpful in this situation str_match(x, ".*\\?\\s(.*)")[, 2] #[1] "Michael Sneider" ...

Patterns (preferably java) find floor space in sq ft

java,regex,pattern-matching

I would try with: Pattern regex = Pattern.compile("(?<= )\\d(\\d*[,\\.]?\\d+)*(?=[ .]?sq)"); where: (?<= ) - there is space before \d - starts with digit (\d*[,\.]?\d+)* - next is digit or digits, there could be comma or point with more digits - and it can repeats like in 100,000,000 (?=[ .]?sq) -...

Preventing move semantics during pattern matching

pattern-matching,rust,move

Why? When you make the tuple (p.choice, p.age) you memcpy both p.choice and p.age from your Person. It's OK to do this for p.age because it's a Copy type - you can continue using the old value after memcpying from it. p.choices is of type Choices which is not Copy....

Matching positive integer with haskell

haskell,pattern-matching,ghc

Although @Sebastian response is correct, yes you can {-# LANGUAGE ViewPatterns #-} import Prelude hiding (odd) data Peano = Zero | Succ Peano deriving Show data PeanoInt = Neg Peano | Pos Peano deriving Show odd :: PeanoInt -> Bool odd (Neg Zero) = False odd (Pos Zero) = False...

Delete some lines from text using Linux command

linux,shell,sed,grep,pattern-matching

The -v option to grep inverts the search, reporting only the lines that don't match the pattern. Since you know how to use grep to find the lines to be deleted, using grep -v and the same pattern will give you all the lines to be kept. You can write...

Does scala support one default clause for many pattern matching?

scala,pattern-matching

I would rewrite the code to make it easier to read: (first, second, third, fours) match { case ("something", s: String, MyEnum.A, _) => //some logic case ("something", s: String, MyEnum.B, Some(old)) => //some other logic case _ => defaulLogic } If you write it this way, the default case...

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

scala,tree,sum,pattern-matching,case-statement

This works. @marios answer led me to the right path, even though his implementation had a bug and didn't work. def leafSum(lst: List[Any]): Int = { lst.foldLeft(0) { case (sum, node: List[_]) => sum + leafSum(node) case (sum, leaf: Int) => sum + leaf } } ...