This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
Closed 2 years ago.
In this string:
jdbc:sqlserver://testserver.apple.com\A4534:54623
I want to match "testserver" "apple.com//A4534" and "54623"
Regex:
jdbc:sqlserver:(.+)\.(.+):(.+)
But I get,
"testserver.apple" "com//A4534" and "54623"
I suggest the following regex:
jdbc:sqlserver:\/\/(\w+).(.+):(\w+)
Explanation:
\/ specifies the /
\w+ specifies word character i.e. [A-Za-z0-9_]+
Check this for a demo.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = " jdbc:sqlserver://testserver.apple.com\\A4534:54623";
Pattern pattern = Pattern.compile("jdbc:sqlserver:\\/\\/(\\w+).(.+):(\\w+)");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1) + "\n" + matcher.group(2) + "\n" + matcher.group(3));
}
}
}
Output:
testserver
apple.com\A4534
54623
Related
Is there a way to use a regex expression with wild cards? Specifically, I have a String phrase and another String target. I would like to use the match method to find the first occurrence of the target in the phrase where the character before and after the target is anything other than a-z.
Updated:
Is there a way to use the String method matches() with the following regex:
"(?<![a-z])" + "hello" + "(?![a-z])";
You can use the regex, "(?<![a-z])" + Pattern.quote(phrase) + "(?![a-z])"
Demo at regex101 with phrase = "hello".
(?<![a-z]): Negative lookbehind for [a-z]
(?![a-z]): Negative lookahead for [a-z]
Java Demo:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
// Test
String phrase = "hello";
String regex = "(?<![a-z])" + Pattern.quote(phrase) + "(?![a-z])";
Pattern pattern = Pattern.compile(regex);
Stream.of(
"hi hello world",
"hihelloworld"
).forEach(s -> {
Matcher matcher = pattern.matcher(s);
System.out.print(s + " => ");
if(matcher.find()) {
System.out.println("Match found");
}else {
System.out.println("No match found");
}
});
}
}
Output:
hi hello world => Match found
hihelloworld => No match found
In case you want the full-match, use the regex, .*(?<![a-z]) + Pattern.quote(phrase) +(?![a-z]).* as demonstrated at regex101.com. The pattern, .* means any character any number of times. The rest of the patterns are already explained above. The presence of .* before and after the match will ensure covering the whole string.
Java Demo:
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
// Test
String phrase = "hello";
String regex = ".*(?<![a-z])" + Pattern.quote(phrase) + "(?![a-z]).*";
Stream.of(
"hi hello world",
"hihelloworld"
).forEach(s -> System.out.println(s + " => " + (s.matches(regex) ? "Match found" : "No match found")));
}
}
Output:
hi hello world => Match found
hihelloworld => No match found
Hi,
I need to create a regex pattern that will pick the matching string starts with '{{' and ends with
"}}" from a given string.
The pattern I have created is working same with the strings starting with '{{{' and '{{', Similarly with ending with '}}}' and
'}}'
Output of above code:
matches = {{phone2}}
matches = {{phone3}}
matches = {{phone5}}
**Expected Output**:
matches = {{phone5}}
I need only Strings which follows two consecutive pattern of '{' and '}' not three.
Sharing the code below
package com.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
public static void main(String[] args) {
String text = "<test>{{#phone1}}{{{phone3}}}{{/phone4}} {{phone5}}></test>";
//String pattern = "\\{\\{\\s*?(\\w*?)\\s*?(?!.*\\}\\}\\}$)";
String pattern = "\\{\\{\\s*?(\\w*?)\\s*?}}";
Pattern placeholderPattern = Pattern.compile(pattern);
Matcher placeholderMatcher = placeholderPattern.matcher(text);
while (placeholderMatcher.find()) {
System.out.println("matches = " + placeholderMatcher.group());
}
}
}
You may use
String pattern = "(?<!\\{)\\{{2}\\s*(\\w*)\\s*\\}{2}(?!\\})";
Or, if empty or blank {{...}} are not expected, use
String pattern = "(?<!\\{)\\{{2}\\s*(\\w+)\\s*\\}{2}(?!\\})";
See the regex demo.
Details
(?<!\{) - a negative lookbehind failing the match if there is a { char immediately to the left of the current location
\{{2} - {{ substring
\s* - 0+ whitespaces
(\w*) - Group 1: one or more word chars (1 or more if + quantifier is used)
\s* - 0+ whitespaces
\}{2} - }} string
(?!\}) - a negative lookahead that fails the match if there is a } char immediately to the right of the current location.
See the Java demo:
String text = "<test>{{#phone1}}{{{phone3}}}{{/phone4}} {{phone5}}></test>";
String pattern = "(?<!\\{)\\{{2}\\s*(\\w*)\\s*\\}{2}(?!\\})";
Pattern placeholderPattern = Pattern.compile(pattern);
Matcher placeholderMatcher = placeholderPattern.matcher(text);
while (placeholderMatcher.find()) {
System.out.println("Match: " + placeholderMatcher.group());
System.out.println("Group 1: " + placeholderMatcher.group(1));
}
Output:
Match: {{phone5}}
Group 1: phone5
This question already has answers here:
Check and extract a number from a String in Java
(16 answers)
Closed 3 years ago.
How to prevent or catch String for which the user has entered an int or a number?
ex.
String name=JOptionPane.showInputDialog("Enter Dog owner's First and Last name");
then if I input Dave Har1234, I want to catch that number on the input then return to the JOptionPane.
I think you should only check if the complete string is a number. For that use the following check inp.matches("\\d")
You can check a complete example here https://onecompiler.com/java/3v5pffkbz
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main
{
public static void main(String[] args) {
String inputStr = "abc00123xyz4560"; // Input String for matching
String regexStr = "[0-9]+"; // Regex to be matched
Pattern pattern = Pattern.compile(regexStr);
Matcher matcher = pattern.matcher(inputStr);
while (matcher.find()) {
System.out.println("find() found substring \"" + matcher.group()
+ "\" starting at index " + matcher.start()
+ " and ending at index " + matcher.end());
}
}
}
you can try this code to catch if user has entered any number in between string.
Can run and check code here: https://www.onlinegdb.com/online_java_compiler
This question already has answers here:
Match exact string
(3 answers)
Closed 3 years ago.
I am creating a regex to support the following patterns
Documents/OneDrive/Collections/book.xlsx
Documents/OneDrive/Collections/book.xls
Documents/OneDrive/Collections/book.xlsm
book 2.xls
aa.xlsx
Attempt
^([a-zA-Z0-9 ]+[/])*([a-zA-Z0-9 ])
"+[.](xls[xm]?"
This regex matches all the required patterns but how can i just limit to the last character.
My guess is that you might want an expression similar to:
^(([a-z0-9\s]+\/)+)?([a-z0-9\s]+)\.[a-z]+
or:
^(([a-z0-9\s]+\/)+)?([a-z0-9\s]+)\.(xlsx?m?)$
Demo 1
Demo 2
Test
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "^(([a-z0-9\\s]+\\/)+)?([a-z0-9\\s]+)\\.[a-z]+";
final String string = "Documents/OneDrive/Collections/book.xlsx\n"
+ "Documents/OneDrive/Collections/book.xls\n"
+ "Documents/OneDrive/Collections/book.xlsm\n"
+ "book 2.xls\n"
+ "aa.xlsx\n\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
RegEx Circuit
jex.im visualizes regular expressions:
This question already has answers here:
Java: splitting a comma-separated string but ignoring commas in parentheses
(4 answers)
Closed 5 years ago.
I want to cut this text
UNIT=1111,SPACE=(TRK,0),DISP=(MOD,DELETE,DELETE),DSN=UUU.AAAAA.BBBBB
Result :
UNIT=1111
SPACE=(TRK,0)
DISP=(MOD,DELETE,DELETE)
DSN=UUU.AAAAA.BBBBB
I tried myself but I m so noob with regular expression, I used (\S+)=(\S+) to cut it but it not work correct.
Someone could help me ?
Here is my java code
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "(\\S+)=(\\S+)";
final String string = "UNIT=1111,SPACE=(TRK,0),DISP=(MOD,DELETE,DELETE),DSN=UUU.AAAAA.BBBBB"
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
You can use this negative lookahead regex for splitting:
String[] arr = str.split(",(?![^()]*\\))");
This is assuming ( and ) are all balanced and unescaped.
RegEx Demo
RegEx Breakup:
,: Match a literal comma
(?![^()]*\\)): Negative lookahead to assert that comma is not inside a (...)
Working code ise here https://regex101.com/r/G355nS/2
^(UNIT=\d{4}),(SPACE=\S+\d+\)),(DISP=\S+\)),(DSN=[\S+.]*)$