Check if string contains single backslashes with regex - regex

I have tried to fix this for a long time, and i just can't do it.
It could be any string, but this is an example:
"\This string \contains some\ backslashes\"
I need to make a regex that i can use to check that the string contains single backslashes.
I then need to convert the given string into (i can do the conversion):
"\\This string \\contains some\\ backslashes\\"
And then use regex to check that the string no long contains single backslashes.
Btw i dont have to use regex for this, i just need to be able to check the strings somehow.

It seems you just want to check if a string matches a regex pattern partially, namely, if it contains a literal backslash not preceded nor followed with a backslash.
Use
(?<!\\)\\(?!\\)
See the regex demo.
Sample Scala code:
val s = """"\This string\\ \contains some\ backslashes\""""
val rx = """(?<!\\)\\(?!\\)""".r.unanchored
val ismatch = s match {
case rx(_*) => true
case _ => false
}
println(ismatch)
See the Scala online demo.
Note:
"""(?<!\\)\\(?!\\)""".r.unanchored - this line declares a regex object and makes the pattern unanchored, so that no full string match is no longer required by the match block
Inside match, we use case rx(_*) as there is no capturing group defined inside the pattern itself
The pattern means: match a backslash (\\) that is not preceded with a backslash ((?<!\\)) and is not followed with a backslash ((?!\\)).

Not sure what you're asking.. are you asking how to write a String literal that represents the String you gave as an example? You could either escape the backslash with another backslash, or use triple quotes.
scala> "\\This string \\contains some\\ backslashes\\"
String = \This string \contains some\ backslashes\
scala> """\This string \contains some\ backslashes\"""
String = \This string \contains some\ backslashes\
And replace the backslashes using the same techniques.
scala> "\\This string \\contains some\\ backslashes\\".replace("\\","\\\\")
String = \\This string \\contains some\\ backslashes\\
or
scala> """\This string \contains some\ backslashes\""".replace("""\""","""\\""")
String = \\This string \\contains some\\ backslashes\\
But I have a feeling you want to do something else, like validate input. Maybe you could provide a bit more context?

Try This
val s = """\This string \contains some\ backslashes\"""
s.replaceAll("""\\""","""\\\\""")

Related

Getting words Starting with symbol in dart

I'm trying to parse in Dart long strings containing hashtags, so far I tried various combinations with regexp but I cannot find the right use.
My code is
String mytestString = "#one #two, #three#FOur,#five";
RegExp regExp = new RegExp(r"/(^|\s)#\w+/g");
print(regExp.allMatches(mytestString).toString());
The desidered output would be a list of hahstags
#one #two #three #FOur #five
Thankyou in advance
You should not use a regex literal inside a string literal, or backslashes and flags will become part of the regex pattern. Also, omit the left-hand boundary pattern (that matches start of string or whitespace) if you need to match # followed with 1+ word chars in any context.
Use
String mytestString = "#one #two, #three#FOur,#five";
final regExp = new RegExp(r"#\w+");
Iterable<String> matches = regExp.allMatches(mytestString).map((m) => m[0]);
print(matches);
Output: (#one, #two, #three, #FOur, #five)
String mytestString = "#one #two, #three#FOur,#five";
RegExp regExp = new RegExp(r"/(#\w+)/g");
print(regExp.allMatches(mytestString).toString());
This should match all of the hashtags, placing them into capture groups for you to later use.

Escaping dollars groovy

I'm having trouble escaping double dollars from a string to be used with regex functions pattern/matcher.
This is part of the String:
WHERE oid_2 = $$test$$ || oid_2 = $$test2$$
and this is the closest code I've tried to get near the solution:
List<String> strList = new ArrayList<String>();
Pattern pattern = Pattern.compile("\$\$.*?\$\$");
log.debug("PATTERN: "+pattern)
Matcher matcher = pattern.matcher(queryText);
while (matcher.find()) {
strList.add(matcher.group());
}
log.debug(strList)
This is the debug output i get
- PATTERN: $$.*?$$
- []
So the pattern is actually right, but the placeholders are not found in the string.
As a test I've tried to replace "$$test$$" with "XXtestXX" and everything works perfectly. What am I missing? I've tried "/$" strings, "\\" but still have no solution.
Note that a $ in regex matches the end of the string. To use it as a literal $ symbol, you need to escape it with a literal backslash.
You used "\$\$.*?\$\$" that got translated into a literal string like $$.*?$$ that matches 2 end of string positions, any 0+ chars as few as possible and then again 2 end of strings, which has little sense. You actually would need a backslash to first escape the $ that is used in Groovy to inject variables into a double quoted string literal, and then use 2 backslashes to define a literal backslash - "\\\$\\\$.*?\\\$\\\$".
However, when you work with regex, slashy strings are quite helpful since all you need to escape a special char is a single backslash.
Here is a sample code extracting all matches from the string you have in Groovy:
def regex = /\$\$.*?\$\$/;
def s = 'WHERE oid_2 = $$test$$ || oid_2 = $$test2$$'
def m = s =~ regex
(0..<m.count).each { print m[it] + '\n' }
See the online demo.
Anyone who gets here might like to know another answer to this, if you want to use Groovy slashy strings:
myComparisonString ==~ /.*something costs [$]stuff.*/
I couldn't find another way of putting a $ in a slashy string, at least if the $ is to be followed by text. If, conversely, it is followed by a number (or presumably any non-letter), this will work:
myComparisonString ==~ /.*something costs \$100.*/
... the trouble being, of course, that the GString "compiler" (if that's its name) would recognise "$stuff" as an interpolated variable.

VB.Net regex random string

I have regex code that gets string between 2 strings from TextBox1.
TextBox1 looks something like this:
href="www.example.com/account/05798/john123">
href="www.example.com/account/4970/max16">
href="www.example.com/account/96577/killer007">
href="www.example.com/account/3077/hackerboy1337">
href="www.example.com/account/43210/king42">
So, it will get value from href="www.example.com/account/4321/ to "> (usernames)
The problem is, how to do it? My regex code:
(?<="href=""www.example.com/account/RANDOM_STRING/")(.*?)(?="">)
I know i could replace RANDOM_STRING with \w{4}, but some IDs are 5-digit.
You need a negated character class [^/] that matches any char but a /. So, replace RANDOM_STRING with [^/]*.
Also, in a regex pattern, to match ., you need to escape the dot - \..
Thus, your regex pattern can be fixed as
(?<="href=""www\.example\.com/account/[^/]*/").*?(?="">)
However, you may user a simpler regex with a capturing group:
"href=""www\.example\.com/account/[^/]*/"(.*?)"">
The value you need is in Match.Groups(1).Value.
Or another option would be to do this
Dim strOne As String = "www.example.com/account/43210/king42"
Dim strMain As String = Split(strOne, "/account/")(1)
Dim strSubOne As String = Split(strMain, "/")(0)
Dim strSubTwo As String = Split(strMain, "/")(1)

Incorrect use of regex wildcards

This is not correct use of wildcards ? I'm attempting to match String that contains a date. I don't want to include the date in the returned String or the String value that prepends the matched String.
object FindText extends App{
val toFind = "find1"
val line = "this is find1 the line 1 \n 21/03/2015"
val find = (toFind+".*\\d{2}/\\d{2}/\\d{4}").r
println(find.findFirstIn(line))
}
Output should be : "find1 the line 1 \n "
but String is not found.
Dot does not match newline characters by default. You can set a DOTALL flag to make it happen (I have also added a "positive look-ahead - the (?=...) thingy - since you did not want the date to be included in the match": val find = (toFind+"""(?s).*(?=\d{2}/\d{2}/\d{4})""").r
(Note also, that in scala you do not need to escape special characters in strings, enclosed in a triple-quote pairs ... pretty neat).
The problem lies with the newline in the test string. A .* does not match newlines apparently. Replacing this with .*\\n?.* should fix it. One could also use a multiline flag in the regex such as:
val find = ("(?s)"+toFind+".*\\d{2}/\\d{2}/\\d{4}").r

Scala regular expressions: how to replace a BELL character (\007) in a string

I need to sanitize a String containing a BELL character coming from a JSON document. I don't get how to define the Regex pattern
import scala.util.matching.Regex
def sanitize(dirtyString: String): String = {
val pattern = "\007" // Octal definition or other ???
pattern.r.replaceAllIn(dirtyString, "")
}
Any help?
Try just
dirtyString.replace("\u0007", "");
This would be much faster than using regexp for such task.
See Replace a string by character code instead of regex?