replaceAll error [duplicate] - java

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.

Related

Regular Expression: No match found? [duplicate]

This question already has answers here:
How to escape text for regular expression in Java?
(8 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 5 years ago.
This is what I am trying to do...
Enter Pattern
//*//_//*
Enter Text
hello *_* how are you?
No match found
I know to avoid treating above characters as Metacharacters I need to use these escape sequences.
I don't know how to do with _ (underscore sigh)
I even tried
//* _ //*
Still it didn't work.
code
Scanner sc = new Scanner(System.in);
System.out.println("Enter pattern");
Pattern pattern = Pattern.compile(sc.nextLine());
System.out.println("Enter Text");
Matcher matcher = pattern.matcher(sc.nextLine());
boolean found = false;
while(matcher.find())
{
System.out.println("I found the text" + matcher.group() + "Starting index" + matcher.start() + "Ending at index" + matcher.end());
found = true;
}
if(!found)
{
System.out.println("No match found");
}
If you are trying to match the *_* part of the input, try the following pattern:
\*\_\*

java Dangling meta character '+' [closed]

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 +...

Digits are getting deleted when splitting a string

I have a string from which I need to remove all mentioned punctuations and spaces. My code looks as follows:
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s+]");
System.out.println("spart[0]: " + spart[0]);
System.out.println("spart[1]: " + spart[1]);
System.out.println("spart[2]: " + spart[2]);
System.out.println("spart[3]: " + spart[3]);
I have a string from which I need to remove all mentioned punctuations and spaces. My code looks as follows:
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s+]");
System.out.println("spart[0]: " + spart[0]);
System.out.println("spart[1]: " + spart[1]);
System.out.println("spart[2]: " + spart[2]);
System.out.println("spart[3]: " + spart[3]);
But, I am getting some elements which are blank. The output is:
spart[0]: s
spart[1]: film
spart[2]:
spart[3]: normal
- is a special character in PHP character classes. For instance, [a-z] matches all chars from a to z inclusive. Note that you've got )-_ in your regex.
- defines a range in regular expressions as used by String.split argument so that needs to be escaped
String[] part = line.toLowerCase().split("[,/?:;\"{}()\\-_+*=|<>!`~##$%^&]");
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s]+");

How to escape backslash in Java [duplicate]

This question already has an answer here:
regex: How to escape backslashes and special characters?
(1 answer)
Closed 8 years ago.
I was trying to escape a Json string as an input via Scanner and print to console,
i was not able to escape " \ " by replacing it with " \\ ",
I'm getting PatternSyntaxException
Here is my code
Scanner s = new Scanner(System.in);
String str = s.next();
String s3 = "";
if (str.contains("\\")) {
s3 = str.replaceAll("\\", "\\\\");
System.out.println(s3);
}
Here is my input to scanner
{"name":"nokia"}\
Help me please !
If you are using regex you have to use 4 backslashes \\\\ to parse the backslash as a literal.
So use s3 = str.replaceAll("\\\\", someOtherString);

Need a regular expression to match a word within a multiline source [duplicate]

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"
}

Categories

Resources