Regex statement to replace all underscore with space [duplicate] - regex

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
I can't use methods like Replace so I need a Regex statement that will replace underscores and add a space instead.
I thought that /([^_])/ would at least return the string without the underscore but it only returns certain strings with the first character.

Sample String x is:
val x = "this_string_contains_Underscore_characters."
Use the below command on this string x:
x.split("_").mkString(" ")
or Use replaceAll:
x.replaceAll("_", " ")
In Scala REPL:
scala> val x = "this_string_contains_Underscore_characters."
x: String = this_string_contains_Underscore_characters.
scala> x.split("_").mkString(" ")
res28: String = this string contains Underscore characters.
scala> x.replaceAll("_", " ")
res50: String = this string contains Underscore characters.

Related

How to return/print matches on a string in RegEx in Flutter/Dart? [duplicate]

This question already has an answer here:
How to put all regex matches into a string list
(1 answer)
Closed 1 year ago.
I want to return a pattern through regEx in flutter every time it' found, I tested using the Regex operation it worked on the same string, returning the match after that included match 'text:' to '}' letters, but it does not print the matches in the flutter application.
The code I am using:
String myString = '{boundingBox: 150,39,48,25, text: PM},';
RegExp exp = RegExp(r"text:(.+?(?=}))");
print("allMatches : "+exp.allMatches(myString).toString());
The output print statement is printing I/flutter ( 5287): allMatches : (Instance of '_RegExpMatch', Instance of '_RegExpMatch')
instead of text: PM
Following is the screenshot of how it is parsing on regexr.com
Instead of using a non greedy match with a lookahead, I would suggest using a negated character class matching any char except } in capture group 1, and match the } after the group to prevent some backtracking.
\b(text:[^}]+)}
You can loop the result from allMatches and print group 1:
String myString = '{boundingBox: 150,39,48,25, text: PM},';
RegExp exp = RegExp(r"\b(text:[^}]+)}");
for (var m in exp.allMatches(myString)) {
print(m[1]);
}
Output
text: PM
You need to use map method to retrieve the string from the matches:
String myString = '{boundingBox: 150,39,48,25, text: PM},';
RegExp exp = RegExp(r"text:(.+?(?=}))");
final matches = exp.allMatches(myString).map((m) => m.group(0)).toString();
print("allMatches : $matches");

How to replace a string between two string using regex [duplicate]

This question already has answers here:
Regex Match all characters between two strings
(16 answers)
Closed 4 years ago.
How to replace a string between two string in javascript
StartLine = `/*TESTSTART*/`;
Endline = `/*TESTEND*/`;
OriginalContent = `/*TESTSTART*/
testing
not
working
/*TESTEND*/`;
var e = OriginalContent .replace(/(StartLine)[\s\S]*?(Endline)/,' it's
working
fine');
OUTPUT = `/*TESTSTART*/
it's
working
fine
/*TESTEND*/`
1) How to check if the string contains / in regular exp?
2) if I stored sting in one variable, how can I use this variable in regular exp?
You can escape a / character with a backslash \ if you're using / to start your regular expression. But in this case, since you want to include the value of a variable in your regular expression, you should use a string to represent a regex instead, in which case there is no need to escape / but you should escape other special regex characters such as * with two backslashes, and you can simply concatenate the variable with the other string literals and variables to form the full regex:
StartLine = '/\\*TESTSTART\\*/';
Endline = '/\\*TESTEND\\*/';
...
var e = OriginalContent.replace(StartLine + '[\s\S]*?' + Endline, "it's
working
fine");

How to use \R in java 8 regex [duplicate]

This question already has answers here:
Difference between matches() and find() in Java Regex
(5 answers)
Closed 5 years ago.
I am trying to use the new \R regex matcher from java 8.
However, for the following code :
public static void main(String[] args)
{
String s = "This is \r\n a String with \n Different Newlines \r and other things.";
System.out.println(s);
System.out.println(Pattern.matches("\\R", s));
if (Pattern.matches("\\R", s)) // <-- is always false
{
System.out.println("Matched");
}
System.out.println(s.replaceAll("\\R", "<br/>")); //This is a String with <br/> Different Newlines <br/> and other things.
}
The Pattern.matches always returns false, where as the replaceAll method does seem to find a match and does what I want it to. How do I make the Pattern.matches work ?
I have also tried the long about way and still can't get it to work :
Pattern p = Pattern.compile("\\R");
Matcher m = p.matcher(s);
boolean b = m.matches();
System.out.println(b);
Well matches (both in String and Matchers classes) attempts to match the complete input string.
You need to use matcher.find instead:
Pattern p = Pattern.compile("\\R");
Matcher m = p.matcher(s);
boolean b = m.find();
System.out.println(b);
From Java docs:
\R Matches any Unicode line-break sequence, that is equivalent to \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]
PS; If you want to know if input contains a line-break then this one liner will work for you:
boolean b = s.matches("(?s).*?\\R.*");
Note use of .* on either side of \R to make sure we are matching complete input. Also you need (?s) to enable DOTALL mode to be able to match multiline string with .*

Scala: How to replace all consecutive underscore with a single space?

I want to replace all the consecutive underscores with a single space. This is the code that I have written. But it is not replacing anything. Below is the code that I have written. What am I doing wrong?
import scala.util.matching.Regex
val regex: Regex = new Regex("/[\\W_]+/g")
val name: String = "cust_id"
val newName: String = regex.replaceAllIn(name, " ")
println(newName)
Answer: "cust_id"
You could use replaceAll to do the job without regex :
val name: String = "cust_id"
val newName: String = name.replaceAll("_"," ")
println(newName)
The slashes in your regular expression don't belong there.
new Regex("[\\W_]+", "g").replaceAllIn("cust_id", " ")
// "cust id"
A string in Scala may be treated as a collection, hence we can map over it and in this case apply pattern matching to substitute characters, like this
"cust_id".map {
case '_' => " "
case c => c
}.mkString
Method mkString glues up the vector of characters back onto a string.

Scala multiline string extraction using regular expression [duplicate]

This question already has answers here:
How do I match any character across multiple lines in a regular expression?
(26 answers)
Closed 3 years ago.
Given a collection of strings which start all with prefix _abc_ABC( and end with suffix ), for instance,
val a = """_abc_ABC(
{
x = 1
y = 2
})"""
how to define a regular expression that strips out the prefix and suffix above ?
This would work:
val a = """_abc_ABC(
{
x = 1
y = 2
})"""
val Re = """(?s)_abc_ABC\((.*)\)""".r
a match { case Re(content) => println(content) }
The (?s) makes it match over multiple lines.