英文:
How can I cleanse a String to contain only digits (0-9) and the letter X (uppercase) only, using Java and Javascript
问题
我正在接受用户输入的ISBN号码 - 可能包含空格和连字符等,并尝试将其清理为仅包含数字。
在Java和JavaScript中,我已经成功地使用了以下正则表达式。
Java(isbn是java.lang.String)
isbn = isbn.replaceAll("[^\\d]", "");
和 JavaScript
isbn = isbn.replace(/[^\d]/g, "");
然而,一些ISBN号码的校验字符可以是X。例如,Sara Reinke的《The book of days》的ISBN号码是'155404295X'。
如何修改正则表达式以允许X以及数字?
更新:在JavaScript中,[^\dX]
起作用了,但是在Java中 [^\\dX]
不起作用。
更新2:问题出在用户(程序员)身上!我在两个地方进行了清理 - 我更新了一个地方但没有更新另一个地方。[^\\dX]
在Java中也是起作用的。
英文:
I am taking an ISBN input by the user - may contain spaces and hyphens etc. - and trying to sanitise it to be only digits.
In Java and Javascript, I have used the following regex successfully
Java (isbn is a java.lang.String)
isbn = isbn.replaceAll("[^\\d]", "");
and, JavaScript
isbn = isbn.replace(/[^\d]/g, "");
However, some ISBNs can have an X as their checksum character. For example, 'The book of days' by Sara Reinke is '155404295X'
How can I change the regex to allow X as well as digits?
Update: [^\dX]
worked in JavaScript, but [^\\dX]
does not work in Java.
Update 2: PEBKAC! I was sanitising in two places - I updated one but not the other. [^\\dX]
does work in Java as well.
答案1
得分: 0
Sure, here's the translation:
你能在那里尝试使用[^0-9X]
吗?我认为它在Java和JavaScript中都可以工作。
附:但是在Java中\\d
也可以工作...
英文:
Can you try [^0-9X]
there? I think it will work in both Java and JavaScript.
P.S. But \\d
should work in Java too...
答案2
得分: 0
如果您想遵循您的解决方案,您可以使用?:(values)进行排除。
对于您的示例,应为:[^\d?:(X)]
,在在线Java正则表达式中进行了测试。
英文:
If you wanna follow your solution you can exclude with ?:(values)
For your example it would be: [^\d?:(X)]
tested in online java regex.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论