w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Scala Regex Pattern Match not able to get it to work
With the repeated group, you only get the last match. To get them all, use findFirstMatchIn or similar. There are certainly duplicate questions. scala> val r0 = "([a-z]+)".r.unanchored r0: scala.util.matching.UnanchoredRegex = ([a-z]+) scala> val m0 = r0 findFirstMatchIn x m0: Option[scala.util.matching.Regex.Match] = Some(abc) scala> val r1 = "(\.?[a-z]+)".r.unanchored r1: scala.util.matching.UnanchoredRegex = (.?[a-z]+) scala> val m1 = r1 findFirstMatchIn m0.get.after m1: Option[scala.util.matching.Regex.Match] = Some(.def) scala> r1 findFirstMatchIn m1.get.after res2: Option[scala.util.matching.Regex.Match] = Some(.hij)

Categories : Regex

Setting a regex optional group to None in Scala
I'm going to copy the code from the accepted answer on the linked question, and without giving credit too. Here it is: object Optional { def unapply[T](a: T) = if (null == a) Some(None) else Some(Some(a)) } val tableNamePattern(database, Optional(schema), tablename) = fullyQualifiedTableName PS: I just today wondered on twitter whether creating special-case extractors was as common as they were suggested. :)

Categories : Regex

Scala using regex with or syntax in match case statement
An "anchored" regex for pattern matching matches whole inputs: val aorb = ".*(a|b).*".r "with a " match { case aorb(_) => "have a or b" case _ => "None" } // res0: String = have a or b If you have capturing groups in your regex you should also use or explicitly ignore results: note _ in aorb(_).

Categories : Scala

Javascript match regex against group
You have WAY too many backslashes, you're only looking for a single word character, and you're only looking for matches right at the beginning of the string. var regexp = /{{(w+)}}/g;

Categories : Javascript

Match contents surrounded by optional group in Java regex
I don't think that this is a solvable problem. From your givens, these are all acceptable: ~foo/~/ ~foo/ foo~/ So, now, let's consider this combination: ~foo/foo~/ What happens here? We have combined the second example and the third example to create an instance of the first example. How do you suggest a correct splitting? As far as I can tell, there's no way to tell if we should be taking the entire expression as one or two valid expressions. Hence, I don't think it's possible to break it up accurately based on your listed restrictions.

Categories : Java

Use regex to retrive a certian part of a string
Use the below regex. regex = src.match(/.images.*/i); console.log(regex[0]); Check this fiddle Demo EDIT Actually the dot at the start in the regex would match any character, so you could even replace that with the forward slash for this case. (forward slash is a special char, so escaped with a backward slash) regex = src.match(//images.*/i);

Categories : Javascript

Scala, how to access the whole match: X match {case Y(z) as matched =>
You should be able to use the @ syntax: x match { case matched @ Y(z) => // do stuff both with "matched" and "z" here ... ... } From here

Categories : Scala

Regex to match paths that don't match a specific pattern: Express Router
The following regex will match any path except those starting with /foo/ app.get(/^/([^f][^o][^o]|.{1,2}|.{4,})/.*$/, routes.index); I assume that this is a standard javascript regex.

Categories : Regex

Regex to match single new line. Regex to match double new line
To match exactly N repetitions of the same character you need lookaheads and lookbehinds (see Match exactly N repetitions of the same character). Since javascript doesn't support the latter, a pure regexp solution seems to be impossible. You'll have to use a helper function, for example: > x = "...a...aa...aaa...aaaa...a...aa" "...a...aa...aaa...aaaa...a...aa" > x.replace(/a+/g, function($0) { return $0.length == 2 ? '@@' : $0; }) "...a...@@...aaa...aaaa...a...@@"

Categories : Javascript

Regex to match only till first occurence of class match
You were missing ? Your regex would be (?i)(.*?)case[^a-zd]*(d+)(.*) You can toggle case insensitive match using (?i) in regex

Categories : Regex

Scala: How to pattern match scala.Long and java.lang.Long
It should work straight away: object LongTest { def test(value: Any): Boolean = value match { case l: Long => true case _ => false } def run() { println(test(1L)) println(test(new java.lang.Long(1L))) } } LongTest.run() // true and true It wasn't obvious to me that you want to match classes instead of instance. I'm not sure I understand what you actually want. Like this? object LongTest { def test(clazz: Class[_]): Boolean = clazz == classOf[Long] || clazz == classOf[java.lang.Long] def run() { println(test(1L.getClass)) println(test(new java.lang.Long(1L).getClass)) } } LongTest.run() // true and true Or as a pattern match: def test(clazz: Class[_]): Boolean = clazz match { case q if q == classOf[Long] || q == classOf[j

Categories : Scala

Regex - Find the match that is inside a match
You can try this regex: /href=[^>]+.pdf/ regex101 demo Most of the time, when you can avoid .* or .+ (or their lazy versions), it's better :) Also, don't forget to escape periods.

Categories : PHP

Regex that match if the match contains special word
You're kind of on the right track with lookahead assertions: {{START}}(?:(?!{{END}})[sS])*specialword(?:(?!{{END}})[sS])*{{END}} Explanation: {{START}} # Match {{START}} (?: # Match... (?!{{END}}) # ...as long as we haven't reached {{END}} yet: [sS] # any character )* # any number of times. specialword # Match "specialword" (?: # Match (as before)... (?!{{END}}) # whatever follows, unless it's {{END}} [sS] )* {{END}} # Then finally match {{END}}

Categories : Regex

Java regex: need one regex to match all the formats specified
Try using a reluctant quantifier: _year:.*?s. .replaceAll("_year:.*?\s", "_year:Y ") System.out .println("utc-hour_of_year:2013-07-30T17 dsfsdgfsgf utc-week_of_year:2013-W31 dsfsdgfsdgf" .replaceAll("_year:.*?\s", "_year:Y ")); utc-hour_of_year:Y dsfsdgfsgf utc-week_of_year:Y dsfsdgfsdgf

Categories : Java

PHP regex, how can I make my regex only return one group?
preg_match_all is returning exactly what is supposed to. The first element is the entire string that matched the regex. Every other element are the capture groups. If you just want the the capture group, then just ignore the 1st element. preg_match_all('/hello:"(.*?)"}/', 'hello:"abcdefg"},"other stuff', $arr, PREG_PATTERN_ORDER); $firstMatch = $arr[1];

Categories : PHP

Regex.Match() won't match a substring
Try removing ^ and $: Regex regex = new Regex(@"[ABCEGHJKLMNPRSTVXY]{1}d{1}[A-Z]{1} *d{1}[A-Z]{1}d{1}", RegexOptions.None); ^ : The match must start at the beginning of the string or line. $ : The match must occur at the end of the string or before at the end of the line or string. If you want to match only in word boundaries you can use  as suggested by Mike Strobel: Regex regex = new Regex(@"[ABCEGHJKLMNPRSTVXY]{1}d{1}[A-Z]{1} *d{1}[A-Z]{1}d{1}", RegexOptions.None);

Categories : C#

regex not returning match but there is clearly a match
You need to escape the dollar sign. start = '>$' end = '</td>' AnnualDiv = re.search('%s(.*)%s' % (start, end), s).group(1) The reason is that the $ is a special character in regex. (It matches the end of a string or before the newline.) This will set AnnualDiv to the string '0.48'. If you want to add the $, you can do it using this: AnnualDiv = "$%s" % re.search('%s(.*)%s' % (start, end), s).group(1)

Categories : Python

Javascript regex to match a regex
A regular expression to match a regular expression is //((?![*+?])(?:[^ [/\]|\.|[(?:[^ ]\]|\.)*])+)/((?:g(?:im?|mi?)?|i(?:gm?|mg?)?|m(?:gi?|ig?)?)?)/ To break it down, / matches a literal / (?![*+?]) is necessary because /* starts a comment, not a regular expression. [^ [/\] matches any non-escape sequence character and non-start of character group [...] matches a character group which can contain an un-escaped /. \. matches a prefix of an escape sequence + is necessary because // is a line comment, not a regular expression. (?:g...)? matches any combination of non-repeating regular expression flags. So ugly. This doesn't attempt to pair parentheses, or check that repetition modifiers are not applied to themselves, but filters out most of the other ways that regular expressions

Categories : Javascript

Scala Set match case
Set defines an isEmpty method so the simplest solution is def test(originalSet: Set[Int]): Boolean = originalSet.isEmpty When you match against a List using list match { case Nil => true case x :: y => false } you are matching against the List Nil object and against the :: class i.e. it is equivalent to list match { case Nil => true case ::(x, y) => false } So you can't use this form with Set. When you pattern match against a List using: list match { case List(a, b) => true case _ => false } you are using the List extractor. The List extractor is defined using unapplySeq which matches if the list is of the given format. Set does not define an unapply or unapplySeq method, so you can't match against it in this way either.

Categories : Scala

Conditional group by in Scala
This will work: val reportsGroup1 = reports.groupBy(p => p.building.getOrElse("")) val reportsGroup2 = reportsGroup1 flatMap { case (key, value) => value.groupBy(v => v.serial.getOrElse("")).map { case (key2, value) => ((key, key2), value) } } We take each of the groups of the first groupBy and do a groupBy on it, then add the first key back in. Each of these separate groups of groups are combined and returned as one map.

Categories : Scala

How to match scala generic type?
You could use ClassTag. val string = implicitly[ClassTag[String]] def getValue[T : ClassTag] = implicitly[ClassTag[T]] match { case `string` => "String" case ClassTag.Int => "Int" case _ => "Other" } Or TypeTag: import scala.reflect.runtime.universe.{TypeTag, typeOf} def getValue[T : TypeTag] = if (typeOf[T] =:= typeOf[String]) "String" else if (typeOf[T] =:= typeOf[Int]) "Int" else "Other" Usage: scala> getValue[String] res0: String = String scala> getValue[Int] res1: String = Int scala> getValue[Long] res2: String = Other If you are using 2.9.x you should use Manifest: import scala.reflect.Manifest def getValue[T : Manifest] = if (manifest[T] == manifest[String]) "String" else if (manifest[T] == manifest[Int]) "

Categories : Scala

how to match a string to a method result in scala?
The value used in the case cannot be a function call. You could achieve what you want in a couple of ways. Either define a val to be equal to the method call's result before the match code, and use that val in the case statement (note that the val name will need to start with a capitol letter as this is special syntax to tell the compiler to use the val, not simply assign the name to the vlaue under test), like this: val text = "str2" val Check = test("str", 1) text match { case "str" => println("str") // how to match result return by 'test' methed? case Check => println("str1") } Or else use a filter in the case statement, as follows: case str if (str == test("str", 1)) => println("str1")

Categories : Scala

Scala: returning results from a case match
def find(teamId: Int = 0) { = is missing, explaining why your method doesn't return anything (Unit). Should be: def find(teamId: Int = 0) = {

Categories : Scala

Scala Type Erasure on Option Match
This is warning you that there is no way at runtime to determine if the value is Some[Test] and not, say, Some[Int], or Some[anything else]. This is due to the JVM not knowing about type parameters (i.e. the same reason that we have type erasure in Java). The post you reference shows a way provided in Scala to get around this type erasure issue, should you really need to ensure that you have a Some[Test] and not any other sub-type of Some. In your case, that does not appear to be relevant, so I wouldn't sweat the warning. On the other hand, more idiomatic (and practical!) would be the following: def f(x: Any) = x match { case Some(y) => println(s"x matched to Some - wrapped value is $y") case None => println("None matched") } This matches to Some[Any], but also provides t

Categories : Scala

Can I force scala to error on an inexhaustive match?
Consider asking questions about your build process. You should be doing a full, clean build (not incremental) and running unit tests immediately prior to code commit/check-in. This to avoid (potential, remaining) bugs in SBT or your build process. You are, of course, expected to monitor the results for errors and warnings. Are you, or perhaps should you be, doing Continuous Integration (automatic, scheduled build/tests)? During such you may have, or introduce, some control over how warnings are addressed (ignored or trigger build failure/warning). I don't see way to do this from the scalac command line. If all other approaches don't meet your needs then consider as a last resort, and then only if appropriate to your build tooling: create a wrapper script for scalac, also named scalac

Categories : Scala

Group a list of Scala Ints into different intervals?
You will want groupBy: val xs = List(103, 206, 101, 111, 211, 234, 242, 99) xs.groupBy(_ / 100) // Map(0 -> List(99), 1 -> List(103, 101, 111), ...) grouped just creates subsequent clumps of a given size, not looking at the actual elements. takeWhile just takes the leading elements as long as a predicate holds. You can use the withDefaultValue method on the resulting map to make it appear as an indexed sequence, where some entries are empty: val ys = xs.groupBy(_ / 100) withDefaultValue Nil ys(0) // List(99) ys(4) // List() !

Categories : Scala

Scala regex ignorecase
Try something like this: "\s(?i)(?:I{1,3}|IV|VI{0,3}|I?X)\s" where the (?i) enables case insensitive matching. Note that you might want to use word boundaries instead of space chars: "\b(?i)(?:I{1,3}|IV|VI{0,3}|I?X)\b" otherwise "Mark iii." won't match.

Categories : Regex

Looking for non-zero property TOs: Can I match a Description with number property, but use a regex match?
It is known that integer types has to be passed as integers in the description rendering the usage of regular expressions useless unfortunately. I do not have a QTP installation at hand right now, but to investigate it further, what happens if you use Print Browser("myBrowser").WebElement("height:=11").ChildObjects.Count and Print Browser("myBrowser").WebElement("height:=^[1-9][0-9]*$").ChildObjects.Count Where "myBrowser" is your browser definition of course.

Categories : Regex

Multiline regex capture in Scala
If you want to activate the dotall mode in scala, you must use (?s) instead of (?m) (?s) means the dot can match newlines (?m) means ^ and $ stand for begining and end of lines

Categories : Regex

How to match sequence group?
If you're still looking for PHP code. function getSequence($str) { $prev = 0; $next = 0; $length = strlen($str); $temp = ""; for($i = 0; $i < $length; $i++) { $next = ord($str[$i]); if ($next == $prev + 1) { $temp .= $str[$i]; } else { if (strlen($temp) > 1) $result[] = $temp; $temp = $str[$i]; } $prev = $next; } if (strlen($temp) > 1) $result[] = $temp; return $result; } $str = "abcwhateverdefwhatever34567whatever012"; print_r(getSequence($str));

Categories : Regex

How to match against the pattern of a partial function's case definition in a Scala macro?
First of all, there is a special flavor of quasiquotes specifically for CaseDefs called cq: override def transformCaseDefs(trees: List[CaseDef]) = trees map { case caseDef @ cq"$pattern if $guard => $body" => ... } Secondly, you should use pq to deconstruct patterns: pattern match { case pq"$name @ $nested" => ... case pq"$extractor($arg1, $arg2: _*)" => ... ... } If you are interested in internals of trees that are used for pattern matching they are created by patvarTransformer defined in TreeBuilder.scala On the other hand if you're are working with UnApply trees (that are being produced after typechecking) I have bad news for you: quasiquotes currently don't support them. Follow SI-7789 to get notified when this is fixed.

Categories : Scala

Scala string interpolation. `raw` prefix in regex
What version of Scala are you using? Works fine in 2.10.0: Welcome to Scala version 2.10.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_37). Type in expressions to have them evaluated. Type :help for more information. scala> raw"d".r res0: scala.util.matching.Regex = d

Categories : Scala

Scala: matching a String against a List of Regex
Well you yourself solved it. There are many ways. One of the idiomatic way is: val patterns = List(new Regex("hello, (.*)", "substr"), new Regex("hi, (.*)", "substr")) patterns.foreach{ x => str match { case x(substr) => { someVar = substr; someVar2 = "defaultValue" } case _ => ; } } In case, if you wish to replace defaultValue with the index of regex it matched then: val i = patterns.zipWithIndex i.foreach{ x => str match { case x._1(substr) => { someVar = substr; someVar2 = "defaultValue - "+x._2 } case _ => ; } }

Categories : Regex

Match character from a group of characters in php
You need array for chars collection and in_array() function that checks if a particular element is in the array: $chars = array('a', 'f', 'h', 'k'); if (in_array('f', $chars)) { echo 'hello'; }

Categories : PHP

Match sum of values to value totals by group
I think what you want may be something like: =SUMIF(A:A,A2,C:C)=B2 applied to the top non-header row and copied down to suit. This, for each Num, sums the lines total and compares it to the Total for the corresponding Num. Result for your example is TRUE in every case.

Categories : Excel

Regex right match url with DOT at the end
The simplest fix is to require a non-punctuation character as the last character: /(^|[?s])(www.[^? ]+/[^/ ]*?[^? ]*[^?.,! ]|www.[^? ]*[^?.,! ])/g Note that I removed some of your backslash, because they were not necessary. JSFiddle. However, this is still by for not a robust URL pattern. So, why reinvent the wheel instead of just using some established URL pattern?

Categories : Javascript

Regex to match this
You can try this pattern: ^(?:[^e ]+|Be|e(?!xception))+.php:d+$ or this pattern, if you don't need to check a specific line format: ^(?>[^e ]++|Be|e(?!xception))+$ Notice: If you need to select all consecutive lines in one block, you just need to remove from the character classes.

Categories : Regex

Given regex does not match to the end
You need to pass the global modifier. I'm not sure which programming language you are using, but the syntax often resembles the following: /$myregex/g For example, given the following text: Hello Adam, how are you? Hello Sarah, how are you? The regular expression /Hellos(.*),/g will match both Adam and Sarah.

Categories : Python

Regex match everything after
Why not using a mix of preg_match() and explode()?: $str = '/events/display/id/featured'; $pattern = '~/events/(?P<method>.*?)/(?P<parameter>.*)~'; preg_match($pattern, $str, $matches); // explode the params by '/' $matches['parameter'] = explode('/', $matches['parameter']); var_dump($matches); Output: array(5) { [0] => string(27) "/events/display/id/featured" 'method' => string(7) "display" [1] => string(7) "display" 'parameter' => array(2) { [0] => string(2) "id" [1] => string(8) "featured" } [2] => string(11) "id/featured" }

Categories : PHP

Regex to match [] but not []
http://rubular.com/r/16q3jSPHN0 [^\](?:]?([(.+?)])) should work for most cases. Edit: Seems like this will not match [test][test], as Rory pointed out. For that, I can't really think of a good solution without using multiple regexps, but if you want just one then try this: http://rubular.com/r/QBqFAbqW9E (?:[^\](?:]?([(.+?)]))|((?:]?([(.+?)])))\) Match groups will be populated in the first 3 if it a block with escaped brackets occurs after a regular block, and the last 3 if the opposite occurs. Match 1 1. 2. 3. [test] 4. [test] 5. test Match 2 1. [test] 2. test 3. 4. 5.

Categories : Javascript



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.