The following returns no matches:
String patternStr = "((19\\d{2}|20\\d{2})-([0-2]\\d{2}|3[0-5]\\d)-(([0-1]\\d|2[0-3])[0-5]\\d[0-5]\\d))";
String fullPath = aFile.getAbsolutePath();
// fullPath should expand to this: "/home/user1/2013-023-135159_abcd_001/File.txt"
Pattern p = Pattern.compile(patternStr);
Matcher m = p.matcher(fullPath);
if (m.matches())
{
System.out.println("Matches found");
}
It should match the date portion, 2013-023-135159. I tested it online and the regex looks OK.
You will need to use:
m.find()
instead of:
m.matches()
As your regex is matching the parts of the input string not fully as expected by m.matches()
RegEx Demo
Related
I have been struggling to find the matched string(s) with Java Regular expression for the syntax {//<some string>/<some String>}
My regular expression should return with these matched cases: {//data/process_id}
Below is the String which i want to find matched syntax:
#process_id={//data/process_id}##history_id={//data/history_id}##Pdataxml={//data/dataxml}##Prules =_UNESCAPEXMLVALUE({//data/rules})##submitted_by={//data/submitted_by}##table_definition={//data/table_definition}
I have tried with below regx pattern but it did not work:
[a-zA-Z_/\\[\\]\\(\\)0-9|]+
Can someone please help me to solve this issue?
You can use the following regex:
\{\/\/[^\/{}\s]*\/[^\/{}\s]*\}
Demo on regex101
code:
String input = "#process_id={//data/process_id}##history_id={//data/history_id}##Pdataxml={//data/dataxml}##Prules =_UNESCAPEXMLVALUE({//data/rules})##submitted_by={//data/submitted_by}##table_definition={//data/table_definition}";
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("\\{\\/\\/[^\\/{}\\s]*\\/[^\\/{}\\s]*\\}").matcher(input);
while (m.find()) {
allMatches.add(m.group());
}
System.out.println(allMatches);
output:
[{//data/process_id}, {//data/history_id}, {//data/dataxml}, {//data/rules}, {//data/submitted_by}, {//data/table_definition}]
Try this regex with a Matcher:
"\\{//([^/]+)/([^/}]+)}"
The parts are captured in groups 1 and 2.
Like this:
Matcher m = Pattern.compile("\\{//([^/]+)/([^/}]+)}").matcher(str);
while (m.find()) {
String part1 = m.group(1);
String part2 = m.group(2);
// do something with the parts
}
To just grab the whole thing, which would be got from m.group(), use this regex:
"(?<=\\{)//[^/]+/[^/}]+(?=})"
I have a string email = John.Mcgee.r2d2#hitachi.com
How can I write a java code using regex to bring just the r2d2?
I used this but got an error on eclipse
String email = John.Mcgee.r2d2#hitachi.com
Pattern pattern = Pattern.compile(".(.*)\#");
Matcher matcher = patter.matcher
for (Strimatcher.find()){
System.out.println(matcher.group(1));
}
To match after the last dot in a potential sequence of multiple dots request that the sequence that you capture does not contain a dot:
(?<=[.])([^.]*)(?=#)
(?<=[.]) means "preceded by a single dot"
(?=#) means "followed by # sign"
Note that since dot . is a metacharacter, it needs to be escaped either with \ (doubled for Java string literal) or with square brackets around it.
Demo.
Not sure if your posting the right code. I'll rewrite it based on what it should look like though:
String email = John.Mcgee.r2d2#hitachi.com
Pattern pattern = Pattern.compile(".(.*)\#");
Matcher matcher = pattern.matcher(email);
int count = 0;
while(matcher.find()) {
count++;
System.out.println(matcher.group(count));
}
but I think you just want something like this:
String email = John.Mcgee.r2d2#hitachi.com
Pattern pattern = Pattern.compile(".(.*)\#");
Matcher matcher = pattern.matcher(email);
if(matcher.find()){
System.out.println(matcher.group(1));
}
No need to Pattern you just need replaceAll with this regex .*\.([^\.]+)#.* which mean get the group ([^\.]+) (match one or more character except a dot) which is between dot \. and #
email = email.replaceAll(".*\\.([^\\.]+)#.*", "$1");
Output
r2d2
regex demo
If you want to go with Pattern then you have to use this regex \\.([^\\.]+)# :
String email = "John.Mcgee.r2d2#hitachi.com";
Pattern pattern = Pattern.compile("\\.([^\\.]+)#");
Matcher matcher = pattern.matcher(email);
if (matcher.find()) {
System.out.println(matcher.group(1));// Output : r2d2
}
Another solution you can use split :
String[] split = email.replaceAll("#.*", "").split("\\.");
email = split[split.length - 1];// Output : r2d2
Note :
Strings in java should be between double quotes "John.Mcgee.r2d2#hitachi.com"
You don't need to escape # in Java, but you have to escape the dot with double slash \\.
There are no syntax for a for loop like you do for (Strimatcher.find()){, maybe you mean while
I have string as follows
"ValueFilter("val1") AND ColumnFilter("val2") AND ValueFilter("val3")"
I have stored the following regex in a array. Using for loop I tried to match the pattern
"ValueFilter\\((.*?)\\)","ColumnFilter\\((.*?)\\)"
what I will do is I will replace the value in the bracket and copy it to a new string.
When I run this above regex against the string in the first loop i have XFilter so it will match both occurrence. But I want to do this in order.
Here is the i thing i want to achieve
first i want to match ValueFilter first then ColumnFilter then again ValueFilter. How can I achieve this?
Edit : Added Code
String expr = "\"ValueFilter(\"val1\") AND ColumnFilter(\"val2\") AND ValueFilter(\"val3\")\"";
String patterns = {"ValueFilter\\((.*?)\\)", "ColumnFilter\\((.*?)\\)"}
for (String pattern : patterns) {
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(expr);
while (m.find()) {
//do something
}
}
Expected Output
ValueFilter("val1")
ColumnFilter("val2")
ValueFilter("val3")
You can use this regex [XY]Filter\((.*?)\) with pattern and you have to loop throw the matches using :
String str = "\"XFilter(\"val1\") AND YFilter(\"val2\") AND XFilter(\"val3\")\"";
String regex = "[XY]Filter\\((.*?)\\)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
Note you can i use [XY] which mean to match both X or Y,
Output
XFilter("val1")
YFilter("val2")
XFilter("val3")
regex demo
If you want to get only the value you can get the group 1 like matcher.group(1) instead, the output should be :
"val1"
"val2"
"val3"
Edit
what if I have filtername as "ValueFilter" and "ColumnFilter" instead
of X and Y
In this case you can use (Value|Column) instead of [XY] which mean match ValueFilter or ColumnFilter, the regex should look like :
String str = "\"ValueFilter(\"val1\") AND ColumnFilter(\"val2\") AND ValueFilter(\"val3\")\"";
String regex = "(Value|Column)Filter\\((.*?)\\)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
Output
ValueFilter("val1")
ColumnFilter("val2")
ValueFilter("val3")
Check code demo
I want to match every file name which ends with .js and is stored in a directory called lib.
Therefore I created the following regular expression: (lib/)(.*?).js$.
I tested the expression (lib/)(.*?).js$ in a Regex Tester and matched this filename: src/main/lib/abc/DocumentHandler.js.
To use my expression in Java, I escaped it to: (lib/)(.*?)\\.js$.
Nevertheless, Java tells me that my expression does not match.
Here is my code:
String regEx = "(lib/)(.*?).js$";
String escapedRegEx = "(lib/)(.*?)\\.js$";
Pattern pattern = Pattern.compile(escapedRegEx);
Matcher matcher = pattern.matcher("src/main/lib/abc/DocumentHandler.js");
System.out.println("Matches: " + matcher.matches()); // false :-(
Did I forgot to escape something?
Use Matcher.find() instead of Matcher.matches() to check for subset of any string.
As per Java Doc:
Matcher#matches()
Attempts to match the entire region against the pattern.
Matcher#find()
Attempts to find the next subsequence of the input sequence that matches the pattern.
sample code:
String regEx = "(lib/)(.*)\\.js$";
String str = "src/main/lib/abc/DocumentHandler.js";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(str);
if (matcher.find()) { // <== returns true if found
System.out.println("Matches: " + matcher.group());
System.out.println("Path: " + matcher.group(2));
}
output:
Matches: lib/abc/DocumentHandler.js
Path: abc/DocumentHandler
Use Matcher#group(index) to get the matched group that is grouped by enclosing inside parenthesis (...) in the regex pattern.
You can use String#matches() method to match the whole string.
String regEx = "(.*)(/lib/)(.*?)\\.js$";
String str = "src/main/lib/abc/DocumentHandler.js";
System.out.println("Matched :" + str.matches(regEx)); // Matched : true
Note: Don't forget to escape dot . that has special meaning in regex pattern to match any thing other than new line.
Try this RegEx pattern
String regEx = "(.*)(lib\\/)(.*)(\\.js$)";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher("src/main/lib/abc/DocumentHandler.js");
It's working for me:
Firstly you don't need to escape it, and secondly you are not matching the first part of the string.
String regEx = "(.*)(lib/)(.*?).js$";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher("src/main/lib/abc/DocumentHandler.js");
How could I get the first and the second text in "" from the string?
I could do it with indexOf but this is really boring ((
For example I have a String for parse like: "aaa":"bbbbb"perhapsSomeOtherText
And I d like to get aaa and bbbbb with the help of Regex pattern - this will help me to use it in switch statement and will greatly simplify my app/
If all that you have is colon delimited string just split it:
String str = ...; // colon delimited
String[] parts = str.split(":");
Note, that split() receives regex and compilies it every time. To improve performance of your code you can use Pattern as following:
private static Pattern pColonSplitter = Pattern.compile(":");
// now somewhere in your code:
String[] parts = pColonSplitter.split(str);
If however you want to use pattern for matching and extraction of string fragments in more complicated cases, do it like following:
Pattert p = Patter.compile("(\\w+):(\\w+):");
Matcher m = p.matcher(str);
if (m.find()) {
String a = m.group(1);
String b = m.group(2);
}
Pay attention on brackets that define captured group.
Something like this?
Pattern pattern = Pattern.compile("\"([^\"]*)\"");
Matcher matcher = pattern.matcher("\"aaa\":\"bbbbb\"perhapsSomeOtherText");
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Output
aaa
bbbbb
String str = "\"aaa\":\"bbbbb\"perhapsSomeOtherText";
Pattern p = Pattern.compile("\"\\w+\""); // word between ""
Matcher m = p.matcher(str);
while(m.find()){
System.out.println(m.group().replace("\"", ""));
}
output:
aaa
bbbbb
there are several ways to do this
Use StringTokenizer or Scanner with UseDelimiter method