I have the following regex
def formula = math:min(math:round($$value1$$ * $$value2$$) )
def m = formula =~ /\$\$\w+\$\$/
println m.group(1)
Above should ideally print $$value1$$.
Now this regex for the following string works fine on regex101.com but same does not work on Groovy. Ideally it should find two groups $$value1$$ and $$value2$$ using Matcher API, but it does not.
Is there anything wrong in this regex?
Assuming formula is:
def formula = 'math:min(math:round($$value1$$ * $$value2$$) )'
I think you just want:
List result = formula.findAll(/\$\$\w+\$\$/)
I tried your regex in java and it works for me if i remove the / at the beginning and the end of the regex.
public class RegexTest {
public static void main(String[] args) {
String regex = "\\$\\$\\w+\\$\\$";
String test = "math:min(math:round($$value1$$ * $$value2$$) ) ";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(test);
while (matcher.find()){
System.out.println(matcher.group());
}
}
}
it returns
$$value1$$
$$value2$$
Related
I am doing a list.where filter:
String needleTemp = '';
final String hayStack =
[itemCode, itemDesc, itemCodeAlt, itemDescAlt, itemGroup].join(' ');
for (final k in query.split(" ")) {
needleTemp = '$needleTemp(?=.*\\Q$k\\E)';
}
var re = RegExp(needleTemp);
return re.hasMatch(hayStack);
I printed the output for needleTemp and it looks the same as on my regex101 example:
in dart it prints (?=.*\Qa/a\E)(?=.*\Qpatro\E)
basically the same, but nothing matches, not even a simple letter.
Is dart regex different or do I need another syntax?
edit:
Simple example to test in DartPad:
void main() {
print("(?=.*\\Qpatrol\\E)");
var re = RegExp("(?=.*\\Q2020\\E)");
print(re.hasMatch('A/A PATROL 2020'));
}
still returns false
Found the solution:
I just need to remove \Q and \E then RegExp.escape(text_to_escape) inside the needle.
I want to split the following string around +, but I couldn't succeed in getting the correct regex for this.
String input = "SOP3a'+bEOP3'+SOP3b'+aEOP3'";
I want to have a result like this
[SOP3a'+bEOP3', SOP3b'+aEOP3']
In some cases I may have the following string
c+SOP2SOP3a'+bEOP3'+SOP3b'+aEOP3'EOP2
which should be split as
[c, SOP2SOP3a'+bEOP3'+SOP3b'+aEOP3'EOP2]
I have tried the following regex but it doesn't work.
input.split("(SOP[0-9](.*)EOP[0-9])*\\+((SOP)[0-9](.*)(EOP)[0-9])*");
Any help or suggestions are appreciated.
Thanks
You can use the following regex to match the string and by replacing it using captured group you can get the expected result :
(?m)(.*?)\+(SOP.*?$)
see demo / explanation
Following is the code in Java that would work for you:
public static void main(String[] args) {
String input = "SOP3a'+bEOP3'+SOP3b'+aEOP3'";
String pattern = "(?m)(.*?)\\+(SOP.*?$)";
Pattern regex = Pattern.compile(pattern);
Matcher m = regex.matcher(input);
if (m.find()) {
System.out.println("Found value: " + m.group(0));
System.out.println("Found value: " + m.group(1));
System.out.println("Found value: " + m.group(2));
} else {
System.out.println("NO MATCH");
}
}
The m.group(1) and m.group(2) are the values that you are looking for.
Do you really need to use split method?
And what are the rules? They are unclear to me.
Anyway, considering the regex you provided, I've only removed some unnecessary groups and I've found what you are looking for, however, instead of split, I just joined the matches as splitting it would generate some empty elements.
const str = "SOP1a+bEOP1+SOP2SOP3a'+bEOP3'+SOP3b'+aEOP3'EOP2";
const regex = RegExp(/(SOP[0-9].*EOP[0-9])*\+(SOP[0-9].*EOP[0-9])*/)
const matches = str.match(regex);
console.log('Matches ', matches);
console.log([matches[1],matches[2]]);
How do I replace comma and right parantheses at the same time, ,') with ), in groovy?
I tried replaceAll with double escape
value = "('cat','rat',',')";
//Replace ,') with )
value = value.replaceAll('\\,')',')');
Tried these with no luck
How can I replace a string in parentheses using a regex?
How to escape comma and double quote at same time for CSV file?
Your question is a bit cofusing, but to replace ,') you don't need escapes at all. Simply use
def value = "('cat','rat',',')";
println value.replace(",')", ")"); // ('cat','rat',')
However, I think you rather want this result ('cat','rat'). Right?
If so, you can use the following code, using Pattern:
import java.util.regex.Pattern
def value = "('cat','rat',',')";
def pattern = Pattern.compile(",'\\)");
def matcher = pattern.matcher(value);
while (matcher.find()) {
value = matcher.replaceAll(")");
matcher = pattern.matcher(value);
}
println value; // ('cat','rat')
Explanation:
You are creating the second replaceable text with your regex, it's not there when you try to replace it, but get's created as a result of the first replacement. So we create a new matcher in the loop and let it find the string again...
If I have a string like:
s = "This is a simple string 234 something else here as well 4334
and a regular expression like:
regex = ~"[0-9]{3}"
How can I extract all the words from the string using that regex? In this case 234 and 433?
You can use CharSequence.findAll:
def triads = s.findAll("[0-9]{3}")
assert triads == ['234', '433']
Latest documentation of CharSequence.findAll
You have to use capturing groups. You can check groovy's documentation about it:
http://mrhaki.blogspot.com/2009/09/groovy-goodness-matchers-for-regular.html
For instance, you can use this code:
s = "This is a simple string 234 something else here as well 4334"
regex = /([0-9]{3})/
matcher = ( s=~ regex )
if (matcher.matches()) {
println(matcher.getCount()+ " occurrence of the regular expression was found in the string.");
println(matcher[0][1] + " found!")
}
As a side note:
m[0] is the first match object.
m[0][0] is everything that matched in this match.
m[0][1] is the first capture in this match.
m[0][n] is the n capture in this match.
You could do something like this.
def s = "This is a simple string 234 something else here as well 4334"
def m = s =~ /[0-9]{3}/
(0..<m.count).each { println m[it][0] }
Output ( Working Demo )
234
433
def INPUT= 'There,once,was,a man,from,"the , extremely,,,,bad .,, , edge",of
the,"universe, ultimately,, is mostly",empty,,,space';
def REGEX = ~/(\"[^\",]+),([^\"]+\")/;
def m = (INPUT =~ REGEX);
while (true) {
m = (INPUT =~ REGEX);
if (m.getCount()>0) {
INPUT = INPUT.replaceAll(REGEX,'$1!-!$2');
System.out.println(INPUT );
} else {
break;
}
}
I want to get two decimals from a string using a Regex but I get only the first.
getGroupCount is correct but I get always {1} and I don't know why. I'm using GWT 2.5. Here is my code:
private void readOffset(){
RegExp regExp = RegExp.compile("(\\{\\d\\})");
MatchResult matcher = regExp.exec("(cast({1} as float)/{24})");
String val1 = matcher.getGroup(0);
String val2 = matcher.getGroup(1);
}
Why might this be happening?
The operator \d will only yield 1 digit. If you want to get two, you would need to use \d{2}. If you need to match more, you would need to use \d+, where + means 1 or more repetitions of.
Something like so worked for me (Java though, not exactly GWT):
String str = "(cast({1} as float)/{24})";
Pattern p = Pattern.compile("(\\{\\d+\\})");
Matcher m = p.matcher(str);
while(m.find())
{
System.out.println(m.group(1));
}
Yields: {1} and {24}
To learn how to use Regex in GWT client side please go through the Unit test cases in GWT for Regex. Reference - GWT Unit Test for Regex
Also you should be using RegExp and MatchResult from com.google.gwt.regexp.shared.
im to stupid for the regex so i solved it quick and dirty:
private void readOffset(){
String offset = manager.get("offset");
String v1 = offset.substring(offset.indexOf("{")+1, offset.indexOf("}"));
String v2 = offset.substring(offset.lastIndexOf("{")+1, offset.lastIndexOf("}"));
multiplikator.setValue(v1);
divisor.setValue(v2);
/*
RegExp regExp = RegExp.compile(".*({\\d+}).*", "g");
MatchResult matcher = regExp.exec(offset);
boolean matchFound = (matcher != null);
if(matchFound == true && matcher.getGroupCount() == 2){
String val1 = matcher.getGroup(0);
String val2 = matcher.getGroup(1);
multiplikator.setValue(matcher.getGroup(0));
divisor.setValue(matcher.getGroup(1));
}else{
multiplikator.setValue("1");
divisor.setValue("1");
}
*/
}
better solutions are welcome :(