Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have text:
String str = "<HTML> <HEAD>\n" +
"<TITLE>Управление разрывом строк </Title>\n" +
"</HEAD>\n" +
"<BODY>\n" +
"<marquee>Это моя учебная страница.</marquee>\n" +
"<H2>Меня зовут <kbd>Ольга. </kbd></H2>\n" +
"<H3 align=\"center\">Я живу во <em>Владивостоке</em>.</H3>\n" +
"<H4 align=\"right\">Моя маленькая родина - <font face=\"Academy\" color=\"Red\">Сахалин</font>. </H4>\n" +
"<H5 align=left>ДВГУ - ВУЗ в котором я работаю.</H5>\n" +
"<B>Здесь</B>\n" +
"<I>продемонстрированы</I>\n" +
"<Blink>различные</Blink>\n" +
"<U> способы </U>\n" +
"<KBD>управления </KBD>\n" +
"<FONT SIZE=5 COLOR=FF80C0>шрифтом:</FONT> его\n" +
"<FONT SIZE=5 COLOR=FF00FF>цветом</FONT> и\n" +
"<FONT SIZE=+3 COLOR=FF00FF>размером.</FONT>\n" +
"</BODY> </HTML>";
I write regexp (?<=(=))[+a-zA-Z0-9]+(?=(>| )) that find manches
left
5
FF80C0
5
FF00FF
+3
FF00FF
But java throw exception
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+3
^
at java.util.regex.Pattern.error(Pattern.java:1955)
at java.util.regex.Pattern.sequence(Pattern.java:2123)
...
Ok. I try shield + ((?<=(=))[\\+a-zA-Z0-9]+(?=(>| )))
But this no work(is the same error). Why?
code:
Matcher matcher = Pattern.compile("(?<=(=))[+a-zA-Z0-9]+(?=(>| ))").matcher(str);
while (matcher.find()) {
str= str.replaceAll(matcher.group(),'"' + matcher.group() + '"');
}
You error has nothing to do with the shown regex.
The problem is because you use the matched result values as a parameter to replaceAll(), and those parameters are also regular expressions.
Since you don't want them to be interpreted as regex, you need to escape them, or rather "quote" them, like this:
str = str.replaceAll(Pattern.quote(matcher.group()),
Matcher.quoteReplacement('"' + matcher.group() + '"'));
UPDATE
However, if you just want to put double-quotes around the matched strings, why don't you just use replaceAll() directly? Like this:
str = str.replaceAll("(?<==)([+a-zA-Z0-9]+)(?=[> ])", "\"$1\"");
Your issue does not come from your pattern, it comes from
replaceAll(...)
ReplaceAll takes a regex in input.
Your input comes from your str, and at some point it is "+3", which contain a dangling +...
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I would like to validate an input (of type String) which have delimiters (only "," or ";") followed by a number of specific length e.g. input1=444554; 445148, 41412; and input2=414454, 784554, etc.
My guess is that this expression might likely validate that:
^(.*?)=\K(\s*([0-9]{6})\s*[;,])+\s*$
and we can add more boundaries, if we wish to, for instance we can change (.*?) with input names, if necessary.
In this demo, the expression is explained, if you might be interested.
Test
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "^(.*?)=\\K(\\s*([0-9]{6})\\s*[;,])+\\s*$";
final String string = "input1=444554; 445148, 414121;\n"
+ "input1=444554; 445148, 41412;\n"
+ "input2=414454, \n"
+ "input1=444554; 44514, 414121;\n"
+ "input1=444554; 445141, 414121; 414121\n"
+ "input2:414454, ";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
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));
}
}
I have assumed that
input1=444554; 445141, 414121; 414121
is undesired since it is not followed by , or ;.
Edit:
Demo
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Everything is explained in the comments
Scanner sc=new Scanner(System.in);
//asking for the verb
System.out.println("Donnez un verbe regulier du premier groupe :");
//putting the verb in the string
String chaine=sc.nextLine();
//taking the two last elements
char first=chaine.charAt(chaine.length());
char second=chaine.charAt(chaine.length()-1);
//creating a StringBuilder:
StringBuilder sb=new StringBuilder();
//putting string in the builder :
sb.append(chaine);
//deleting the two last characters :
sb.deleteCharAt(sb.length()-1);
//printing elemnts :
System.out.println("Je "+sb.append("e"));
System.out.println("Tu "+sb.append("es"));
System.out.println("Il/Elle "+sb.append("e"));
System.out.println("nous "+sb.append("ons"));
System.out.println("vous "+sb.append("ez"));
System.out.println("Ils/Elles "+sb.append("ent"));
I got StringIndexOutOfBoundsException.
I can help more according to your questions.
String radical = chaine.replaceFirst("..$", "");
System.out.println("Je " + radical + "e");
System.out.println("Tu " + radical + "es");
System.out.println("Il/Elle " + radical + "e");
System.out.println("Nous " + radical + "ons");
System.out.println("Vous " + radical + "ez");
System.out.println("Ils/Elles " + radical + "ent");
This uses a regular expression replaceFirst. The pattern:
. any character
. any character
$ end of string
Hence: the last two letters are replaced by the empty string.
The minor advantage over chaine.substring(0, chaine.length() - 2)
is that for the empty string or one-letter string no indexing error happens;
it does no replacing. Admittedly substring is faster.
Your code is full of errors.
First:
char first=chaine.charAt(chaine.length());
char second=chaine.charAt(chaine.length()-1);
Will throw an exception because the last character of chaine is chaine.length()-1. So you should have written:
char first=chaine.charAt(chaine.length()-1);
char second=chaine.charAt(chaine.length()-2);
or perhaps:
char first=chaine.charAt(chaine.length()-2);
char second=chaine.charAt(chaine.length()-1);
but you don't seem to do anything with first and second.
Next, StringBuilder.append will append the parameter to the builder, I don't think that's what you wont.
Perhaps you wanted to do:
String prefix = chaine.substring(0, chaine.length()-2);
System.out.println("Je " + prefix + "e");
System.out.println("Tu " + prefix + "es");
System.out.println("Il/Elle " + prefix + "e");
System.out.println("Nous " + prefix + "ons");
System.out.println("Vous " + prefix + "ez");
System.out.println("Ils/Elles " + prefix + "ent");
This question already has answers here:
String.replaceAll single backslashes with double backslashes
(5 answers)
Closed 5 years ago.
This is my regex. I want to find the opening and closing parentheses and replace them with "\(" and "\)".
word = word.replaceAll(Pattern.quote("("), "\\" + "(").replaceAll(Pattern.quote(")"), "\\" + ")");
This is the output if word = "word)":
New word is: word)
As you can see it didn't change a thing.
Try to use \\\\ like this :
word = word.replaceAll(Pattern.quote("("), "\\\\" + "(")
.replaceAll(Pattern.quote(")"), "\\\\" + ")");
or without Pattern.quote :
word = word.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)");
or instead in your case you can just use replace :
word = word.replace("(", "\\(").replace(")", "\\)");
Two answers worked:
word.replace("(", "\\" + "(").replace(")", "\\" + ")"); – OH GOD SPIDERS
and
replacing \\ with \\\\ in the replaceAll - YCF_L.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am searching the body of the constructor(s) of classes to find out any composition association between classes. So I have decided to use the following regex to perform this matching:
String regex = "(" + "^[this.]" + attribute.getName() + "=" + "|" + "^[this.]" + attribute.getName() + " =" + "|" + "^" + attribute.getName() + "=" + "|" + "^" + attribute.getName() + "=" + ")";
A class member might be initialized in the constructor in the following formats:
this.objectName =...; (with empty space)
this.objectName=...; (without empty space)
objectName =...; (with empty space)
objectName=...; (without empty space)
However, my regex still doesn't work as I expected.
Let's assume that I have initialized Student student; in the following constructor:
public Submission(long studentID, Date dateSubmitted, float grade){
this.studentID = studentID;
this.student= new Student();
this.grade = grade;
this.dateSubmitted = dateSubmitted;
}
And my regex should be dynamically created as:
String regex = "( ^[this.]student= | ^[this.]student = | ^student= | ^student = )";
if we assume that body is the content of the Submission(..) constructor
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(body);
if(m.find()) { ((ClassStructure)abstractStructure).addAssociation(AssociationType.COMPOSITION, node.getName());
isFound = true;
}
isFound should be initialized as true at the end of the compilation. In fact, it is not.
Could you please tell me how should I re-write the regex?
Since you are searching for this keyword in the beginning of the line, you don't get the desired results. Try to change your regex with this;
String regexTwo = "( (?:this\.)?" + attribute.getName() + "= | " + "(?:this\.)?" + attribute.getName() + " = )";
I have solved the problem by the help of Andreas and Erdi Izgi. The following regex works perfectly:
String regexTwo = "( (?:this\\.)?" + attribute.getName() + "= | " + "(?:this\\.)?" + attribute.getName() + " = )";
This question already has answers here:
Match multiline text using regular expression
(4 answers)
Closed 9 years ago.
I need a regular expression to match the very first word within the following source:
WanRoutingProtocol=
Static
192.160.22.0/27
false
2004:BA2:78::50
=IAS
I just want to extract the very first word (In this case "Static") using a regular expression in java.
The blank lines contains multiple newlines.
I'm using the following regex
"^(\\n)+Static.*IAS"
but this is not working.
Use the following regex. Expression assumes that the input would always start and end with the keywords "WanRoutingProtocol" and "IAS" and would fetch any keyword present at the place of "Static".
^WanRoutingProtocol=\\s*(.*)[\\s\\w\\./:]*=IAS$
Here's how you could do this in Java. (There's no need to use Pattern.MULTILINE)
String input = "WanRoutingProtocol=\n" +
" Static\n" +
"\n" +
"\n" +
"\n" +
" 192.160.22.0/27\n" +
" false\n" +
"\n" +
" 2004:BA2:78::50\n" +
"\n" +
"\n" +
" =IAS";
Pattern p = Pattern.compile("^WanRoutingProtocol=\\s*(.*)[\\s\\w\\./:]*=IAS$");
Matcher m = p.matcher(input);
while (m.find()) {
System.out.println(m.group(1)); // prints "Static"
}