Extract numbers from String using Regex [duplicate] - java

This question already has answers here:
Matching one string multiple times using regex in Java
(4 answers)
Closed 4 years ago.
I have a string such as below:
String str="tile tile-2 tile-position-1-4"
I wish to receive the numbers in an array,such as [2,1,4].
My own solution is to break the string using split, but i am wondering if there is a shortcut using Regx
Thanks to #nitzien with Regx it tried:
String pattern= "^tile tile-(\\d*) tile-position-(\\d*)-(\\d*)$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
System.out.println(m.group(0));
System.out.println(m.group(1));
System.out.println(m.group(2));
But, it complains with:
java.lang.IllegalStateException: No match found

regex pattern - "^tile tile-(\d*) tile-position-(\d*)-(\d*)$"
replacement - "[\1,\2,\3]"
Replacement is string which you will need to convert to array depending on which language you are using.
Updated answer after edited question
String str="tile tile-2 tile-position-1-4";
String pattern= "^tile tile-(\\d*) tile-position-(\\d*)-(\\d*)$";
System.out.println(str.replaceAll(pattern, "$1,$2,$3"));
This will give
2,1,4

Related

Java regex issue with: ###tag1###value1###tag2###value2###tag3###value3###

I'm having trouble writing a regex to validate the following pattern:
###tag1###value1###tag2###value2###tag3###value3###
This can repeat indefinitely
The tags and values can contain any printable char as well as whitespace and newlines
I've been trying variations of this:
String pattern = "(###[\\p{Print}\\s]+###[\\p{Print}\\s]+)+###"
But it is not enforcing the pattern for certain cases such as:
###testTag###testValue###testtag2testvalue2### (missing the ### for tag2/value2)
And its invalidating some valid inputs such as:
###component###CORE COMMAND GROUP###severity###DEBUG###message###Validating potential model load directory: C:/some/dir/market-xxxxxx/market-xxxxxx-PRODUCT-kit/data/XXX_7020190724201513_0X###
Any suggestions on how I can improve this regex? Thanks!
I'm using the Java pattern lib.
You ma use this regex"
final String regex =
"^(?:###(?:(?!###|###)\\P{C})+###(?:(?!###|###)\\P{C})+)+###$";
RegEx Demo
\P{C} matches any printable unicode character
(?:(?!###|###)\\P{C}) matches any printable unicode character if it is not immediately followed by ### or ###
This works well :
String s1 = "###tag1###value1###tag2###value2###tag3###value3###";
String s2 = "testTag###testValue###testtag2testvalue2###";
String s3 = "component###CORE COMMAND GROUP###severity###DEBUG###message###Validating potential model load directory: C:/some/dir/market-xxxxxx/market-xxxxxx-PRODUCT-kit/data/XXX_7020190724201513_0X###";
String p = "(###|^)?(((\P{C})+?###(\P{C})+?)###|$)+?";
Matcher m1 = p.matcher(s1); // testTag###testValue
Matcher m2 = p.matcher(s2); // tag1###value1, tag2###value2, tag3###value3
Matcher m3 = p.matcher(s3); // component###CORE COMMAND GROUP, severity###DEBUG
This will almost get you there:
(###)((.+?)(###)(.+?)(###))
https://regex101.com/r/5rfpL0/4
I'm just having a hard time figuring out why:
(###)((.+?)(###)(.+?)(###))+
doesn't make it behave as expected :-/

Java is not able to find a match for regex [duplicate]

This question already has answers here:
Rationale for Matcher throwing IllegalStateException when no 'matching' method is called
(6 answers)
Closed 3 years ago.
I have been trying to figure out why java is not able to find nay matches for this regex pattern, I tested it with https://regexr.com/ and it works fine.
But when I escape it and use it in my class it complains about no match found.
Regex pattern I used in regexr.com
pattern: TEST\(":"\)\/(\w+)\[#name="(.*)"\]
Strings to test: TEST(":")/Role[#name="TestRole"]
The website is able to find two groups: 1. Role and 2. TestRole. And thats the required behaviour.
But when I use it in my code my test returns with no match found, here are the escaped pattern and test strings:
public String extractCorrectExp() {
String path1 = "TEST(\":\")/Role[#name=\"TetsRole\"]";
String pattern = "TEST\\(\":\"\\)\\/(\\w+)\\[#name=\"(.*)\"\\]";
Pattern pat = Pattern.compile(pattern);
Matcher match = pat.matcher(path1);
return match.group();
}
It returns:
java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Matcher.java:536)
at java.util.regex.Matcher.group(Matcher.java:496)
Could this be escaping issue? or somehow I am using regex identifiers which are not compatible with java?
find() must be called on the Matcher before group() can be called. Your code will work if you change it to:
String path1 = "TEST(\":\")/Role[#name=\"TestRole\"]";
String pattern = "TEST\\(\":\"\\)/(\\w+)\\[#name=\"(.*)\"]";
Pattern pat = Pattern.compile(pattern);
Matcher match = pat.matcher(path1);
if ( match.find() ) {
System.out.println(match.group());
}
If condition can be used for a single match, and while loop can be used for multiple matches.

Grabbing partial data from URL in Selenium [duplicate]

This question already has answers here:
Parse a URI String into Name-Value Collection
(30 answers)
Closed 4 years ago.
In selenium, is there a way to grab partial dynamically changing data from a URL? Example, I ran driver.getCurrentUrl() in my code and retrieved the below URL. I only want to grab the numeric portion of it and concatenate it so I end up with 819499-1. However, next time I run it the values will be different. Is there a way to capture this information without capturing the entire URL?
http://custmaint/clnt_estimate_overview.jsp?estimateNbr=819499&versionNbr=1&estimateMgmt=true&clntAutoAssign=true
I think this is a more generic question, not only related to Selenium...
Basically, You could use regular expression matching like so:
String url = "http://custmaint/clnt_estimate_overview.jsp?estimateNbr=819499&versionNbr=1&estimateMgmt=true&clntAutoAssign=true";
final Pattern p = Pattern.compile("^.*\\?estimateNbr=(\\d+)&versionNbr=(\\d+).*$");
Matcher m = p.matcher(url);
if (m.find()) {
System.out.print(m.group(1) + "-" + m.group(2));
}
Another approach (more flexible) is to use a dedicated library like httpcomponents; see How to convert map to url query string?
String url = driver.getCurrentUrl();
String estimateNbr = url.substring(url.indexOf("eNbr=")+5, url.indexOf("&v"));
String versionNbr = url.substring(url.indexOf("nNbr=")+5, url.indexOf("&e"));
System.out.println(estimateNbr + "-" + versionNbr);

Regext do not work in java but it does inr egex check [duplicate]

I have a piece of code that I can't make it working on Eclipse with Java 1.7 installed.
There is a regex expression I want to use to match and extract 2 strings from every match, so I am using 2 groups for this.
I have tested my expression in many websites (online regex testers) and it works for them bust it isn't working on my Java project in Eclipse.
The source string looks like anyone of these:
Formal Language: isNatural
Annotation Tool: isHuman%Human Annotator: isHuman
Hybrid Annotation: conceptType%Hybrid Annotation Tool: conceptType%Hybrid Tagset: conceptType
... and so on.
I want to extract the first words before the ":" and the word after for every match.
The regex I'm using is this:
(\w*\s*\w+):(\s+\w+)%{0,1}
And the snippet of code:
String attribute = parts[0];
Pattern pattern = Pattern.compile("(\\w*\\s*\\w+):(\\s+\\w+)%{0,1}");
Matcher matcher = pattern.matcher(attribute);
OWLDataProperty dataProp = null;
if (matcher.matches()){
while (matcher.find()){
String name = null, domain = null;
domain = matcher.group(1);
name = matcher.group(2);
dataProp = factory.getOWLDataProperty(":"+Introspector.decapitalize(name), pm);
OWLClass domainClass = factory.getOWLClass(":"+domain.replaceAll(" ", ""), pm);
OWLDataPropertyDomainAxiom domainAxiom = factory.getOWLDataPropertyDomainAxiom(dataProp, domainClass);
manager.applyChange(new AddAxiom(ontology, domainAxiom));
}
Does anybody of you know why it's not working?
Many thanks.
When using matches(), you are asking if the string you provided matches your regex as a whole. It is as if you added ^ at the beginning of your regex and $ at the end.
Your regex is otherwise fine, and returns what you expect. I recommend testing it regexplanet.com, Java mode. You will see when matches() is true, when it false, and what each find() will return.
To solve your problem, I think you only need to remove the if (matcher.matches()) condition.

How to validate URL in java using regex? [duplicate]

This question already has answers here:
What is the best regular expression to check if a string is a valid URL?
(62 answers)
Closed 9 years ago.
I want to validate url started with http/https/www/ftp and checks for /\ slashes and checks for .com,.org etc at the end of URL using regular expression. Is there any regex patttern for URL validation?
This works:
Pattern p = Pattern.compile("(#)?(href=')?(HREF=')?(HREF=\")?(href=\")?(http://)?[a-zA-Z_0-9\\-]+(\\.\\w[a-zA-Z_0-9\\-]+)+(/[#&\\n\\-=?\\+\\%/\\.\\w]+)?");
Matcher m = p.matcher("your url here");
I am use the following code for that
String lRegex = "^(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]";
btw a search in google and you would find the solution by yourself.

Categories