Implement re.search() functionality in Groovy or Java [duplicate] - java

This question already has answers here:
Create array of regex matches
(6 answers)
Closed 4 years ago.
I need a Groovy/Java function to search for groups in a string based on regular expression
Ex:
function("([\w-]+)-([\w.-]+)\.([\w.-]+)" ,"commons-collections-3.2.2.jar" )
should return a list ["commons-collections" , "3.2.2" , "jar"]
Python can do this by
>> import re
>> re.search("([\w-]+)-([\w.-]+)\.([\w.-]+)" ,"commons-collections-3.2.2.jar" )
>> print(result.groups())
output is ("commons-collections" , "3.2.2" , "jar")

It is a simple and basic task in groovy. Any way I hope this answer will help you.
"commons-collections-3.2.2.jar".findAll(/([\w-]+)-([\w.-]+)\.([\w.-]+)/) {
println it
}
This will produce the output :
[commons-collections-3.2.2.jar, commons-collections, 3.2.2, jar]
Update :
As #tim_yates mentioned in comment,
println "commons-collections-3.2.2.jar".findAll(/([\w-]+)-([\w.-]+)\.([\w.-]+)/) { it.tail() }
This provides better output than above and also more specific to the task.
Output:
[[commons-collections, 3.2.2, jar]]

Related

lambda expression not supporting in stream().allMatch() / .anyMatch() method [duplicate]

This question already has answers here:
Syntax error on token(s), misplaced construct(s) for lambda expression
(2 answers)
Closed 2 years ago.
I'm not getting why JAVA 1.8 is not supporting the lambda expression in stream().filter() / allMatch() / anyMatch()
for example :
ERROR snippet from eclipse IDE
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args) {
// Creating a list of Integers
List<Integer> list = Arrays.asList(3, 4, 6, 12, 20);
// Check if all elements of stream
// are divisible by 3 or not using
// Stream allMatch(Predicate predicate)
boolean answer = list.stream().allMatch(n-> n % 3 ==0);
// Displaying the result
System.out.println(answer);
}
}
I'm getting errors in eclipse as "Syntax error on token "-", -- expected" and red lines below 'n'.
Please help me to understand and resolve this issue.
#NOTE: I'm using eclipse 3.8, JAVA 8 (1.8.0_271)
Your code seem to compile and run in https://www.tutorialspoint.com/compile_java_online.php
Which runs Java 1.8.0_141.
Check if the target run time in eclipse is set to java 8.
You can use Target JRE in Eclipse as an example.

How to reference a method on the object itself [duplicate]

This question already has answers here:
Groovy equivalent of Java 8 :: (double colon) operator
(2 answers)
Closed 4 years ago.
In java I can write
Arrays.asList("test ").stream().map(String::trim);
If I try this in groovy
Arrays.asList("test ").stream().map(String.&trim)
I get
Caught: groovy.lang.MissingMethodException: No signature of method: java.lang.String.trim() is applicable for argument types: (String) values: [test ]
Possible solutions: trim(), wait(), grep(), wait(long), split(java.lang.String), print(java.io.PrintWriter)
What is the correct syntax or do I have to resort to
Arrays.asList("test ").stream().map({ x -> x.trim() })
?
you can use .map { it.trim() } too, but otherwise, groovy does not have method reference working like java one

Need java equivalent of this c# code [duplicate]

This question already has answers here:
Reading a plain text file in Java
(31 answers)
How do I split a string in Java?
(39 answers)
Closed 5 years ago.
Learning file I/O in java, but cant seem to get java to recognize this format in a text document :
A=1
B=2
.
.
.
.
Z=26
What i want is for the letters A through Z to be equal to the int counterpart, I've been able to do this in C# using this code:
var dic = File.ReadAllLines(AplhabetFile)
.Select(l => l.Split(new[] { '=' }))
.ToDictionary(s => s[0].Trim(), s => s[1].Trim());
but i can't seem to find its exact java equivalent anywhere.
Any Ideas ?
You can do the same with Streams:
Map<String, String> dic = Files.lines(Paths.get(AlphabetFile))
.map(l -> l.split("="))
.collect(Collectors.toMap(s -> s[0].trim(), s -> s[1].trim()));

StringUtils or any library class method to preserve the delimiter [duplicate]

This question already has answers here:
How to split a string, but also keep the delimiters?
(24 answers)
Closed 6 years ago.
I am having a string "role1#role2#role3#role4$arole" separated with delimiter # and $. I used below java code
String str = "role1#role2#role3#role4$arole";
String[] values = StringUtils.splitPreserveAllTokens(str, "\\#\\$");
for (String value : values) {
System.out.println(value);
}
And got the result
role1
role2
role3
role4
arole
But my requirement is to preserve the delimiter in the result. So, the result has to be as per requirement
role1
#role2
#role3
#role4
$arole
I analyzed the apache commons StringUtils method to do that but was unable to found any clue.
Any library class to get the above intended results?
You may use a simple split with a positive lookahead:
String str = "role1#role2#role3#role4$arole";
String[] res = str.split("(?=[#$])");
System.out.println(Arrays.toString(res));
// => [role1, #role2, #role3, #role4, $arole]
See the Java demo
The (?=[#$]) regex matches any location in a string that is followed with a # or $ symbol (note the $ does not have to be escaped inside a [...] character class).

Regex matching in python 2.7 [duplicate]

This question already has answers here:
How do you validate a URL with a regular expression in Python?
(12 answers)
Closed 6 years ago.
I am new to Python and would like to know how to have build a regex pattern to match a URL
I have the following code in Java and it works. I need to have a similar one in python
Java:
URI uri = new URI("http://localhost:8080")
Matcher m = Pattern.compile("(.*)" + "/client" + "/([0-9]+)")
.matcher(uri.getPath());
Could someone guide me with having an equivalent regex in Python
Why not use urlparse? Batteries included :-).
>>> import urlparse
>>> urlparse.urlparse("http://localhost:8080")
ParseResult(scheme='http', netloc='localhost:8080', path='', params='', query='', fragment='')
Here's the equivalent in Python 2.7:
import re
from urlparse import urlparse
url = urlparse('http://localhost:8080')
match = re.match(r'(.*)/client/([0-9]+)', url.path)
EDIT
Here's how you would use match to get the individual components (just guessing as to what you want to do next):
if match:
prefix = match.group(1)
client_id = int(match.group(2))

Categories

Resources