I can have string like switchaubcsp-loafsyvgvhv which can possibly contain any of the following patterns: s-loaf, p-loaf etc.
Following is the requirement in detail:
1st character - Any of [p,s,a,r,l],
2nd character -> [-], Followed by Word [loaf].
In the above example, when searched for [p-loaf], Found the text p-loaf starting at 11 index and ending at index 17 using java.util.regex.
What will be the regular expression for finding the first character to be Any of [p,s,a,r,l], 2nd character -> [-], Followed by Word [loaf].
[psarl]-loaf
if you want the word to start with it, add ^ to the beginning and if you want the word to end with it, add $ to the end.
you can try it out here demo regex
import java.util.regex.*;
public class RegexExamples {
public static void main(String[] args) {
RegexTag("devicexyzas-loafcdbdd", "[psarl][-]loaf");
}
public static void RegexTag(Stri`enter code here`ng Content, String PatternToMatch){
Pattern pattern;
try {
pattern = Pattern.compile(PatternToMatch);
}
catch (PatternSyntaxException e)
{
System.err.println ("Regex syntax error: " + e.getMessage ());
System.err.println ("Error description: " + e.getDescription ());
System.err.println ("Error index: " + e.getIndex ());
System.err.println ("Erroneous pattern: " + e.getPattern ());
return;
}
Matcher matcher = pattern.matcher(Content);
System.out.println ("Regex = " + Content);
System.out.println ("Text = " + PatternToMatch);
System.out.println ();
while (matcher.find()) {
System.out.println("Found the text \"" + matcher.group()
+ "\" starting at " + matcher.start()
+ " index and ending at index " + matcher.end());
}
}
}
Related
My problem is that I have a line with multiple usernames and I want to separate each username with a comma. Each username contains first name and last name and also "&" symbol between them.
The first name and last name with same criteria and long for both
I know the way to follow, which is that I have to find the number of letters of the first name (before the symbol "&") and after the symbol I get the same number of letters of the first name (that will be the second name) and therefore I add the comma here.
For Example:
The input line like this:
ramy&hanyfrank&gerry
The output should be like this:
ramy&hany,frank&gerry
======
I tried to implement it, but doesn't work with me as following:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class one {
public static void main(String[] args) {
// String inputText = "ramy&hanyfrank&gerry";
StringBuffer inputText2 = new StringBuffer("ramy&hanyfrank&gerry");
int usernameLength = 0;
Pattern pattern = Pattern.compile("&");
Matcher matcher = pattern.matcher(inputText2);
boolean found = false;
while (matcher.find()) {
System.out.println("I found " + matcher.group() + " starting at index " +
matcher.start() + " and ending at index " + matcher.end());
usernameLength = matcher.start() + matcher.end();
System.out.println(usernameLength);
inputText2.insert(usernameLength, ",");
found = true;
}
System.out.println(inputText2);
if (!found) {
System.out.println("No match found.");
}
}
}
With your code , it would throw index out of bound exception because matcher.start()+matcher.end() is incorrect . It will be out of bound. You need to have last inserted position of , and reduce from it.
You can try below code.
StringBuffer inputText2 = new StringBuffer("ramy&hanyfrank&gerry");
int usernameLength = 0;
Pattern pattern = Pattern.compile("&");
Matcher matcher = pattern.matcher(inputText2);
boolean found = false;
int a= 0;
while (matcher.find()) {
System.out.println("I found " + matcher.group() + " starting at index " +
matcher.start() + " and ending at index " + matcher.end());
usernameLength = matcher.start()-a+matcher.end();
System.out.println(usernameLength);
if (usernameLength<inputText2.length())
inputText2.insert(usernameLength, ",");
a= usernameLength+1;
System.out.println(inputText2);
found = true;
}
System.out.println(inputText2);
if (!found) {
System.out.println("No match found.");
}
I want such a validation that My String must be contains at least one Unicode letter. The character that will evaluate Character.isLetter() to true.
for example i want
~!##$%^&*(()_+<>?:"{}|\][;'./-=` : false
~~1_~ : true
~~k_~ : true
~~汉_~ : true
I know i can use for-loop with Character.isLetter(), but i just don't want to do it.
And This is totally different from this since it only checks for the English alphabets, but in my case is about one unicode letter. It's not a same at all.
You can try to use this regex "\\p{L}|[0-9]"
To better understand Unicode in Regex read this.
Usage code:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
// String to be scanned to find the pattern.
String line = "~!##$%^&*(()_+<>?:\"{}|\\][;'./-=`";
String pattern = "\\p{L}|[0-9]"; // regex needed
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
System.out.print("String \"" + line + "\" results to ");
if (m.find()) {
System.out.println("TRUE -> Found value: " + m.group(0));
} else {
System.out.println("FALSE");
}
line = "~~1_~";
m = r.matcher(line);
System.out.print("String \"" + line + "\" results to ");
if (m.find()) {
System.out.println("TRUE -> Found value: " + m.group(0));
} else {
System.out.println("FALSE");
}
line = "~~k_~";
m = r.matcher(line);
System.out.print("String \"" + line + "\" results to ");
if (m.find()) {
System.out.println("TRUE -> Found value: " + m.group(0));
} else {
System.out.println("FALSE");
}
line = "~~汉_~";
m = r.matcher(line);
System.out.print("String \"" + line + "\" results to ");
if (m.find()) {
System.out.println("TRUE -> Found value: " + m.group(0));
} else {
System.out.println("FALSE");
}
}
}
Result:
String "~!##$%^&*(()_+<>?:"{}|\][;'./-=`" results to FALSE
String "~~1_~" results to TRUE
String "~~k_~" results to TRUE -> Found value: k
String "~~汉_~" results to TRUE -> Found value: 汉
I have written a regex to match following pattern:
Any characters followed by hyphen followed by number followed by space followed by an optional case insensitive keyword followed by space followed by any char.
E.g.,
TXT-234 #comment anychars
TXT-234 anychars
The regular expression I have written is as follows:
(?<issueKey>^((\\s*[a-zA-Z]+-\\d+)\\s+)+)((?i)?<keyWord>#comment)?\\s+(?<comment>.*)
But the above doesn't capture the zero occurrence of '#comment', even though I have specified the '?' for the regular expression. The case 2 in the above example always fails and the case 1 succeeds.
What am I doing wrong?
#comment won't match #keyword. That is why you don't have a match try. This one it should work:
([a-zA-Z]*-\\d*\\s(((?i)#comment|#transition|#keyword)+\\s)?[a-zA-Z]*)
This may help;
String str = "1. TXT-234 #comment anychars";
String str2 = "2. TXT-234 anychars";
String str3 = "3. TXT-2a34 anychars";
String str4 = "4. TXT.234 anychars";
Pattern pattern = Pattern.compile("([a-zA-Z]*-\\d*\\s(#[a-zA-Z]+\\s)?[a-zA-Z]*)");
Matcher m = pattern.matcher(str);
if (m.find()) {
System.out.println("Found value: " + m.group(0));
System.out.println("Found value: " + m.group(1));
System.out.println("Found value: " + m.group(2));
}
m = pattern.matcher(str2);
if (m.find()) {
System.out.println("Found value: " + m.group(0));
}
m = pattern.matcher(str3);
if (m.find()) {
System.out.println("Found value: " + m.group(0));
} else {
System.out.println("str3 not match");
}
m = pattern.matcher(str4);
if (m.find()) {
System.out.println("Found value: " + m.group(0));
} else {
System.out.println("str4 not match");
}
I've been trying to replace this mathematical function x^2*sqrt(x^3) to this pow(x,2)*Math.sqrt(pow(x,3))
so this is the regex
/([0-9a-zA-Z\.\(\)]*)^([0-9a-zA-Z\.\(\)]*)/ pow(\1,\2)
it works in ruby, but I can't find a way to do it in java, I tried this method
String function= "x^2*sqrt(x^3)";
Pattern p = Pattern.compile("([a-z0-9]*)^([a-z0-9]*)");
Matcher m = p.matcher(function);
String out = function;
if(m.find())
{
System.out.println("GRUPO 0:" + m.group(0));
System.out.println("GRUPO 1:" + m.group(1));
out = m.replaceFirst("pow(" + m.group(0) + ", " + m.group(1) + ')');
}
String funcformat = out;
funcformat = funcformat.replaceAll("sqrt\\(([^)]*)\\)", "Math.sqrt($1)");
System.out.println("Return Value :"+ funcion );
System.out.print("Return Value :"+ funcformat );
But still doesn´t work, the output is: pow(x, )^2*Math.sqrt(x^3) as I said before it should be pow(x,2)*Math.sqrt(pow(x,3)).
Thank you!!
As others have commented, regex is not the way to go. You should use a parser. But if you want some quick and dirty:
From Matcher:
Capturing groups are indexed from left to right, starting at one.
Group zero denotes the entire pattern, so the expression m.group(0)
is equivalent to m.group().
So you need to use m.group(1) and m.group(2). And escape the caret ^ in your regex.
import java.util.regex.*;
public class Replace {
public static void main(String[] args) {
String function= "x^2*sqrt(3x)";
Pattern p = Pattern.compile("([a-z0-9]*)\\^([0-9]*)");
Matcher m = p.matcher(function);
String out = function;
if (m.find()) {
System.out.println("GRUPO 0:" + m.group(1));
System.out.println("GRUPO 1:" + m.group(2));
out = m.replaceFirst("pow(" + m.group(1) + ", " + m.group(2) + ')');
}
String funcformat = out;
funcformat = funcformat.replaceAll("sqrt\\(([a-z0-9]*)\\^([0-9]*)]*\\)", "Math.sqrt(pow($1, $2))");
System.out.println("Return Value :"+ function );
System.out.print("Return Value :"+ funcformat );
}
}
I want to replace this file input to a html table:
ip add St Stat Type Mode ip only class numbers
------------------------------ -- ----- ---- ---- --------------- ------ -----
ABC_127.562.200.5/32 - up ABC - 127.562.200.5 5
ABC_127.292.200.3/32 - up ABC - 127.562.200.5 4
ABC_127.262.200.13/32 - up ABC - 127.562.200.5 3
ABC:jdnsajkds
I know this will end with "ABC" but I am not able to figure out why "/" is also coming in input
import java.util.regex.*;
interface LogExample {
public static final int NUM_FIELDS = 7;
public static final String logEntryLine = "ABC_127.562.200.5/32 **space** -- **space** up **space** ABC **space** -- **space** 127.562.200.5 **space** 5 **space** ";
}
public class LogRegExp implements LogExample {
public static void main(String argv[]) {
String logEntryPattern = "";//thats i am not getting
System.out.println("Using RE Pattern:");
System.out.println(logEntryPattern);
System.out.println("Input line is:");
System.out.println(logEntryLine);
Pattern p = Pattern.compile(logEntryPattern);
Matcher matcher = p.matcher(logEntryLine);
if (!matcher.matches() ||
NUM_FIELDS != matcher.groupCount()) {
System.err.println("Bad log entry (or problem with RE?):");
System.err.println(logEntryLine);
return;
}
System.out.println("name + IP Address: " + matcher.group(1));
System.out.println("status1: " + matcher.group(2));
System.out.println("status2: " + matcher.group(3));
System.out.println("type: " + matcher.group(4));
System.out.println("mode: " + matcher.group(5));
System.out.println("IP Address: " + matcher.group(6));
System.out.println("class: " + matcher.group(7));
System.out.println("numbers: " + matcher.group(8));
}
}
Since your class column is blank, we can't do very much to extract that information. But this regex will match the 7 columns of data that you do have:
String logEntryPattern = "(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)";
We need to escape the backslash in the Java string literal.
System.out.println("name + IP Address: " + matcher.group(1));
System.out.println("status1: " + matcher.group(2));
System.out.println("status2: " + matcher.group(3));
System.out.println("type: " + matcher.group(4));
System.out.println("mode: " + matcher.group(5));
System.out.println("IP Address: " + matcher.group(6));
System.out.println("numbers: " + matcher.group(7));
Frankly, a regular expression is a little much for what you're trying to so -- just tokenizing on spaces would work just as well -- but it gets the job done.
I got the solution:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main( String args[] )
{
// String to be scanned to find the pattern.
// String line = "MSEM-E-031_TO_RVBC-R-001_T1 en up TE ingr 124.252.200.2 ELSP 0";
// String pattern = "((\\-{8})+.*?)";
String line = "ADR-SSF-1008-M008 vlan en dn 10081008";
String pattern = "((\\-{6})+.*?)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( ))
{
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
}
else
{
System.out.println("NO MATCH");
}
}
}