I have a requirement where in I want to get two different items form one long string.
I have got below program where in I get required items when I do group(1) and group(6).
But I want to get it in group(1) and group(2).
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
String somepattern = "((123|456)-(0|1)-((\\d-?){8})-\\d{1})/(\\d{2})";
String str = "/somethingwaste/123-0-1234-5678-9/10";
Matcher p = Pattern.compile(somepattern).matcher(str);
while (p.find()) {
System.out.println(p.group(1));
System.out.println(p.group(6));
}
Any pointers directions appriciated.
Thanks
This should do it
String somepattern = "((?:123|456)-[01]-(?:\\d-?){8}-\\d)/(\\d{2})";
The ?: makes a () non-capturing.
Just make the groups you don't want to keep non-capturing using ?::
String somepattern = "((?:123|456)-[01]-(?:\\d-?){8}-\\d)/(\\d{2})";
String str = "/somethingwaste/123-0-1234-5678-9/10";
Matcher p = Pattern.compile(somepattern).matcher(str);
while (p.find()) {
System.out.println(p.group(1));
System.out.println(p.group(2));
}
Related
I am trying to get a single match with regex which contains both parts of the string at once like "BERPAR" in the following text:
{"from":"BER", "comment":"something", "to":"PAR" }
I came up with this (?|from":"([A-Z]{3})"|to":"([A-Z]{3})"), which apparently works fine with PCRE as you can see here
But in the code, I get an error with Java compiler.
Exception in thread "main" java.util.regex.PatternSyntaxException: Unknown inline modifier near index 2
(?|from":"([A-Z]{3})"|to":"([A-Z]{3})")
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.List;
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
String str = "{\"from\":\"BER\", \"comment\":\"something\", \"to\":\"PAR\" }";
System.out.println(str);
Pattern p = Pattern.compile("(?|from\":\"([A-Z]{3})\"|to\":\"([A-Z]{3})\")");
Matcher m = p.matcher(str);
List<String> results = new ArrayList<>();
while(m.find()) {
results.add(m.group(1));
}
System.out.println(results);
}
}
link to the online ide to see the error: http://tpcg.io/DWoebEWG
any solution or workaround would be appreciated.
Please note that the objective is Only use regex. It's first matching group should return "BERPAR"
PLEASE NOTE THAT THIS REGEX IS SUPPOSED TO BE PARSED BY A JAVA APPLICATION I DO NOT HAVE ANY OPTION TO WRITE JAVA CODE FOR IT!
THE ABOVE CODE SNIPPET IS FOR DEMONSTRATION PURPOSE ONLY!
Please note that the objective is Only use regex. It's first matching
group should return "BERPAR"
You can get it by using ((?<=from\":\")|(?<=to\":\"))([A-Z]{3})(?=\") as the regex.
Demo:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HelloWorld {
public static void main(String[] args) {
String str = "{\"from\":\"BER\", \"comment\":\"something\", \"to\":\"PAR\" }";
System.out.println(str);
Pattern p = Pattern.compile("((?<=from\":\")|(?<=to\":\"))([A-Z]{3})(?=\")");
Matcher m = p.matcher(str);
List<String> results = new ArrayList<>();
while (m.find()) {
results.add(m.group());
}
System.out.println(results);
// Join the strings of the list
String joined = String.join("", results);
System.out.println(joined);
}
}
Output:
{"from":"BER", "comment":"something", "to":"PAR" }
[BER, PAR]
BERPAR
I'm new to Java, I'm looking for a stoi()-like function in Java which is in C++.
I want like this:
If there is string like "123ABC", I want extract '123' in Integer and get the index of 'A'.
I've been looking for this, but I couldn't find it. So I upload it here.
In advance, really thank you so much who help me!
Use NumberFormat#parse(String, ParsePosition). The first argument would be "123ABC", the return value will be 123 and the ParsePosition points to A.
You can try following code:
public class Number {
public static void main(String[] args) {
String str = "A1234BCD";
extractDigit(str);
}
public static void extractDigit(String str){
str="A1234AB2C";
String numberOnly= str.replaceAll("[^0-9]", "");
System.out.println(numberOnly);
Pattern pattern = Pattern.compile("\\p{L}");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println(matcher.start());
}
}
I'm trying to figure out how to insert a specific string into another (or create a new one) after a certain string pattern inside the original String.
For example, given this string,
"&2This is the &6String&f."
How would I insert "&l" after all "&x" strings, such that it returns,
"&2&lThis is the &6&lString&f&l."
I tried the following using positive look-behind Regex, but it returned an empty String and I'm not sure why. The "message" variable is passed into the method.
String[] segments = message.split("(?<=&.)");
String newMessage = "";
for (String s : segments){
s.concat("&l");
newMessage.concat(s);
}
System.out.print(newMessage);
Thank you!
You can use:
message.replaceAll("(&.)", "$1&l")
(&.) finds pattern where an ampersand (&) is followed by anything. (&x as you've written).
$1&l says replace the captured group by the captured group itself followed by &l.
code
String message = "&2This is the &6String&f.";
String newMessage = message.replaceAll("(&.)", "$1&l");
System.out.println(newMessage);
result
&2&lThis is the &6&lString&f&l.
My answer would be similar to the one above. It just this way would be reusable and customizable in many circumstances.
public class libZ
{
public static void main(String[] args)
{
String a = "&2This is the &6String&f.";
String b = patternAdd(a, "(&.)", "&l");
System.out.println(b);
}
public static String patternAdd(String input, String pattern, String addafter)
{
String output = input.replaceAll(pattern, "$1".concat(addafter));
return output;
}
}
I have the following code: http://ideone.com/mFUaqG
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegexUtils
{
private static final Pattern resourceURLCSS = Pattern.compile("url\\([\'\"](((?!://).)*)[\'\"]\\)");
private static final Pattern resourceURLHTML = Pattern.compile("(href|src|url)=[\'\"](((?!://).)*)[\'\"]");
public static String makeCSSURLsAbsolute(String input, String baseURL)
{
Matcher matcher = resourceURLCSS.matcher(input);
return matcher.replaceAll("url('"+baseURL+"$1')");
}
public static String makeHTMLURLsAbsolute(String input, String baseURL)
{
Matcher matcher = resourceURLHTML.matcher(input);
return matcher.replaceAll("$1=\""+baseURL+"$2\"");
}
public static void main(String[] args)
{
String fixed = RegexUtils.makeCSSURLsAbsolute("div#header { background-image: url('images/header-background.jpg'); } div#header { background-image: url('images/header-background.jpg'); }", "http://www.google.ca/");
System.out.println(fixed);
fixed = RegexUtils.makeHTMLURLsAbsolute("href=\"wtfguys.css\" href=\"wtfguys.css\"", "http://www.google.ca/");
System.out.println(fixed);
}
}
Unfortunately, this code doesn't do what I expect, which is to replace all occurrences of the regular expression with the string replacement. We are essentially replacing relative URLs in CSS and HTML with absolute URLS. It only seems to replace the first occurrence, giving
div#header { background-image: url('http://www.google.ca/images/header-background.jpg'); } div#header { background-image: url('images/header-background.jpg'); }
href="http://www.google.ca/wtfguys.css" href="wtfguys.css"
as output. Any suggestions?
You are using regexps that attempt to match both single- and double quoted attribute values. The thing is, you may match a truncated value because none of the two patterns makes sure the opening quote matches the closing. Also, that quote should be missing in the value itself.
So, wrap the opening quote into a capture group, use a backrefrence as the closing delimiter and add the backrefrence as an alternative to the lookahead in the tempered greedy token. Then, fix the replacement patterns since the order of backreferences will change.
private static final Pattern resourceURLCSS = Pattern.compile("url\\((['\"])((?:(?!://|\\1).)*)\\1\\)");
private static final Pattern resourceURLHTML = Pattern.compile("(href|src|url)=(['\"])((?:(?!://|\\2).)*)\\2");
public static String makeCSSURLsAbsolute(String input, String baseURL)
{
Matcher matcher = resourceURLCSS.matcher(input);
return matcher.replaceAll("url('"+baseURL+"$2')");
}
public static String makeHTMLURLsAbsolute(String input, String baseURL)
{
Matcher matcher = resourceURLHTML.matcher(input);
return matcher.replaceAll("$1=\""+baseURL+"$3\"");
}
See the IDEONE demo
.* is greedy. The matcher captures wtfguys.css" href="wtfguys.css as $2, not wtfguys.css. You can use .*? or [^\"]* instead, since URLs don't have even escaped quotes inside. Reference for this issue explaining several options (including the one mentioned by Wiktor): http://www.rexegg.com/regex-quantifiers.html#greedytrap.
how can I check to make sure the only special character a string can have is a comma?
testString = "123,34565,222" //OK
testString = "123,123.123." //Fail
A full working example based on #Simeon's regex. This reuses a single Matcher object, which is recommended if the check will be done frequently.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class OnlyLettersDigitsCommas {
//"": Dummy search string, to reuse matcher
private static final Matcher lettersCommasMtchr = Pattern.
compile("^[a-zA-Z0-9,]+$").matcher("");
public static final boolean isOnlyLettersDigitsCommas(String to_test) {
return lettersCommasMtchr.reset(to_test).matches();
}
public static final void main(String[] ignored) {
System.out.println(isOnlyLettersDigitsCommas("123,34565,222"));
System.out.println(isOnlyLettersDigitsCommas("123,123.123."));
}
}
Output:
[C:\java_code\]java OnlyLettersDigitsCommas
true
false
You can use a quick String.contains method like this:
if ( testString.contains(".") {
// fails
}
But I would consider using Regex for this type of validation.
EDIT : As stated in the comments of the question : [a-zA-Z0-9,]
Maybe a
if (!testString.matches("^[a-zA-Z0-9,]+$")) {
// throw an exception
}
check ?