Simple java pattern matching issue? - java

I would like to test if a string contains insert and name, with any interceding characters. And if it does, I would like to print the match.
For the below code, only the third Pattern matches, and the entire line is printed. How can I match only insert...name?
String x = "aaa insert into name sdfdf";
Matcher matcher = Pattern.compile("insert.*name").matcher(x);
if (matcher.matches())
System.out.print(matcher.group(0));
matcher = Pattern.compile(".*insert.*name").matcher(x);
if (matcher.matches())
System.out.print(matcher.group(0));
matcher = Pattern.compile(".*insert.*name.*").matcher(x);
if (matcher.matches())
System.out.print(matcher.group(0));

try to use group like this .*(insert.*name).*
Matcher matcher = Pattern.compile(".*(insert.*name).*").matcher(x);
if (matcher.matches()) {
System.out.print(matcher.group(1));
//-----------------------------^
}
Or in your case you can just use :
x = x.replaceAll(".*(insert.*name).*", "$1");
Both of them print :
insert into name

You just need to use find() instead of matches() in your code:
String x = "aaa insert into name sdfdf";
Matcher matcher = Pattern.compile("insert.*?name").matcher(x);
if (matcher.find())
System.out.print(matcher.group(0));
matches() expects you to match entire input string whereas find() lets you match your regex anywhere in the input.
Also suggest you to use .*? instead of .*, in case your input may contain multiple instances of index ... name pairs.
This code sample will output:
insert into name

Just use multiple positive lookaheads:
(?=.*insert)(?=.*name).+
See a demo on regex101.com.

Related

Extracting a string using Regex

I have the following code to extract the string within double quotes using Regex.
String str ="\"Java\",\"programming\"";
final Pattern pattern = Pattern.compile("\"([^\"]*)\"");
final Matcher matcher = pattern.matcher(str);
while(matcher.find()){
System.out.println(matcher.group(1));
}
The output I get now is java programming.But from the String str I want the content in the second double quotes which is programming. Can any one tell me how to do that using Regex.
If you take your example, and change it slightly to:
String str ="\"Java\",\"programming\"";
final Pattern pattern = Pattern.compile("\"([^\"]*)\"");
final Matcher matcher = pattern.matcher(str);
int i = 0
while(matcher.find()){
System.out.println("match " + ++i + ": " + matcher.group(1) + "\n");
}
You should find that it prints:
match 1: Java
match 2: programming
This shows that you are able to loop over all of the matches. If you only want the last match, then you have a number of options:
Store the match in the loop, and when the loop is finished, you have the last match.
Change the regex to ignore everything until your pattern, with something like: Pattern.compile(".*\"([^\"]*)\"")
If you really want explicitly the second match, then the simplest solution is something like Pattern.compile("\"([^\"]*)\"[^\"]*\"([^\"]*)\""). This gives two matching groups.
If you want the last token inside double quotes, add an end-of-line archor ($):
final Pattern pattern = Pattern.compile("\"([^\"]*)\"$");
In this case, you can replace while with if if your input is a single line.
Great answer from Paul. Well,You can also try this pattern
final Pattern pattern = Pattern.compile(",\"(\\w+)\"");
Java program
String str ="\"Java\",\"programming\"";
final Pattern pattern = Pattern.compile(",\"(\\w+)\"");
final Matcher matcher = pattern.matcher(str);
while(matcher.find()){
System.out.println(matcher.group(1));
}
Explanation
,\": matches a comma, followed by a quotation mark "
(\\w+): matches one or more words
\": matches the last quotation mark "
Then the group(\\w+) is captured (group 1 precisely)
Output
programming

Android Java regexp pattern

I ping a host. In result a standard output. Below a REGEXP but it do not work correct. Where I did a mistake?
String REGEXP ="time=(\\\\d+)ms";
Pattern pattern = Pattern.compile(REGEXP);
Matcher matcher = pattern.matcher(result);
if (matcher.find()) {
result = matcher.group(1);
}
You only need \\d+ in your regex because
Matcher looks for the pattern (using which it is created) and then tries to find every occurance of the pattern in the string being matched.
Use while(matcher.group(1) in case of multiple occurances.
each () represents a captured group.
You have too many backslashes. Assuming you want to get the number from a string like "time=32ms", then you need:
String REGEXP ="time=(\\d+)ms";
Pattern pattern = Pattern.compile(REGEXP);
Matcher matcher = pattern.matcher(result);
if (matcher.find()) {
result = matcher.group(1);
}
Explanation: The search pattern you are looking for is "\d", meaning a decimal number, the "+" means 1 or more occurrences.
To get the "\" to the matcher, it needs to be escaped, and the escape character is also "\".
The brackets define the matching group that you want to pick out.
With "\\\\d+", the matcher sees this as "\\d+", which would match a backslash followed by one or more "d"s. The first backslash protects the second backslash, and the third protects the fourth.

Why does this pattern matching code not work?

I'm trying to do some pattern matching in Java:
Pattern p = Pattern.compile("(\\d+) (\\.+)");
Matcher m = p.matcher("5 soy milk");
String qty = m.group(1);
String name = m.group(2);
I want to end up with one string that contains "5" and one string that contains "soy milk". However, this pattern matching code gives me an IllegalStateException.
You have to call matches() before you attempt to get the groups.
http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#matches()
public boolean matches()
Attempts to match the entire region against the pattern.
If the match succeeds then more information can be obtained via the start, end, and group methods.
Try this:
Pattern p = Pattern.compile("(\\d+) (\\.+)");
Matcher m = p.matcher("5 soy milk");
if (m.matches())
{
String qty = m.group(1);
String name = m.group(2);
}
This is because you don't initiate your Matcher. You should p.matcher(...).matches() (or .find(), or .lookingAt(), depending on the desired behaviour -- real regex matching is done with .find()).
And check the result of .matches() since in your case it returns false: \.+ ("\\.+" in a Java string) will try and match a dot one or more times; you should use .+ (".+" in a Java string) to match "any character, one or more times".

Regular Expression strings in Java

I want to use a regular expression that extracts a substring with the following properties in Java:
Beginning of the substring begins with 'WWW'
The end of the substring is a colon ':'
I have some experience in SQL with using the Like clause such as:
Select field1 from A where field2 like '%[A-Z]'
So if I were using SQL I would code:
like '%WWW%:'
How can I start this in Java?
Pattern p = Pattern.compile("WWW.*:");
Matcher m = p.matcher("zxdfefefefWWW837eghdehgfh:djf");
while (m.find()){
System.out.println(m.group());
}
Here's a different example using substring.
public static void main(String[] args) {
String example = "http://www.google.com:80";
String substring = example.substring(example.indexOf("www"), example.lastIndexOf(":"));
System.out.println(substring);
}
If you want to match only word character and ., then you may want to use the regular expression as "WWW[\\w.]+:"
Pattern p = Pattern.compile("WWW[\\w.]+:");
Matcher m = p.matcher("WWW.google.com:hello");
System.out.println(m.find()); //prints true
System.out.println(m.group()); // prints WWW.google.com:
If you want to match any character, then you may want to use the regular expression as "WWW[\\w\\W]+:"
Pattern p = Pattern.compile("WWW[\\w\\W]+:");
Matcher m = p.matcher("WWW.googgle_$#.com:hello");
System.out.println(m.find());
System.out.println(m.group());
Explanation: WWW and : are literals. \\w - any word character i.e. a-z A-Z 0-9. \\W - Any non word character.
If I understood it right
String input = "aWWW:bbbWWWa:WWW:aWWWaaa:WWWa:WWWabc:WWW:";
Pattern p = Pattern.compile("WWW[^(WWW)|^:]*:");
Matcher m = p.matcher(input);
while(m.find()) {
System.out.println(m.group());
}
Output:
WWW:
WWWa:
WWW:
WWWaaa:
WWWa:
WWWabc:
WWW:

Java RegEx: Just get a part of the matcher group

I have a regex in Java:
Pattern pattern = Pattern.compile(<string>text</string><string>.+</string>);
Matcher matcher = pattern.matcher(ganzeDatei);
while (matcher.find()) {
String string = matcher.group();
...
This works fine, but the output is something like
<string>text</string><string>Name</string>
But I just want this: Name
How can I do this?
Capture the text you want to return by wrapping it in parenthesis, so in this example your regex should become
<string>text</string><string>(.+)</string>
Then you can access the text that matched between the parenthesis with
matcher.group(1)
The no-arg group method you are calling, returns the entire portion of the input text that matches your pattern, whereas you want just a subsequence of that, which matches a capturing group (the parenthesis).
Then do this:
Pattern pattern = Pattern.compile(<string>text</string><string>(.+)</string>);
Matcher matcher = pattern.matcher(ganzeDatei);
while (matcher.find()) {
String string = matcher.group(1);
...
Reference:
Java Tutorial: Regex
Pattern JavaDoc: Capturing Groups
Matcher JavaDoc: Matcher.group(n)
Matcher JavaDoc: Matcher.group()
You must put text you want to obtain by group() into brackets. So use:
<string>(.+)</string>

Categories

Resources