2

According to http://www.regexplanet.com/advanced/java/index.html, my regex

\\uline\{[a-zA-Z\d]+\}|\\text(super|sub)script\{[0-9]+.[0-9]+\}

should work fine to detect e.g. 1) \textsuperscript{1.1} and 2) \uline{name}

Furthermore, replaceFirst works as expected: 12345\textsuperscript{1.1}6789 goes to 123456789

I doubled backslashes and added the regex to my Kotlin code (in IntelliJ Idea):

var stylingRegex = "\\\\uline\\{[a-zA-Z\\d]+\\}|\\\\text(super|sub)script    \\{[0-9]+.[0-9]+\\}"
var testString = "12345\\uline{james}678"
testString = testString.replaceFirst(Pattern.quote(stylingRegex), "")
println("testString: " + testString)

However, what's printed is the initialized string without any modification.

2
  • You should not quote the regex, remove Pattern.quote(), use testString = testString.replaceFirst(stylingRegex.toRegex(), "") Commented Mar 19, 2018 at 11:03
  • Here is a demo showing that Wiktor's suggestion fixes the problem. Commented Mar 19, 2018 at 11:04

1 Answer 1

4

You should not quote the regex pattern and you should make sure you pass a regex to the replaceFirst:

testString = testString.replaceFirst(stylingRegex.toRegex(), "")

See the online Kotlin demo:

var stylingRegex = """\\uline\{[a-zA-Z\d]+\}|\\text(super|sub)script\{[0-9]+\.[0-9]+\}"""
var testString = "12345\\uline{james}678"
testString = testString.replaceFirst(stylingRegex.toRegex(), "")
println("testString: " + testString)
// => testString: 12345678

Note that you do not need to use excessive backslashes when using raw string literals (defined with """...""""), inside them, the \ symbol denotes a literal backslash that is used to create regex escapes.

Also, to match float numbers only, you need to escape the dot in the [0-9]+.[0-9]+ part of your pattern. To match both integer and float, use [0-9]+(?:\.[0-9]+)?.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.